How To Count The Number Of Elements On The First Row Of Their Parent Element
My question is, is there a way maybe in JavaScript that I can determine how many child elements are going to fit across the first row of a parent element? I would then multiply th
Solution 1:
Ok, I think I understand you better now. Try this code out. Run it as is and observe the count, then go to full-screen mode and run it again.
$(document).ready(function(){
function countFirstRowItems(parentSelector, childSelector){
var count = 0, theTop = undefined;
$(parentSelector + " > " + childSelector).each(function(){
var thisTop = $(this).offset().top;
if(theTop === undefined){
theTop = thisTop;
}
if(thisTop != theTop){
return false;
}
count++;
});
return count;
}
$('#btnCount').click(function(){
$('#spnCount').html(
countFirstRowItems('.outer', '.item')
);
});
$('#spnCount').html(
countFirstRowItems('.outer', '.item')
);
});
.outer{
padding:.5em;
margin:.5em;
box-shadow:inset 0px 0px 3px #aaa;
}
.item{
margin:.5em;
height:150px;
width:100px;
border:solid 1px #ddd;
float:left;
background-color:#fdfafa;
}
.clearfix{
clear:both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnCount">Count items on first row</button>
<span id="spnCount">?</span>
<div class='outer'>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='clearfix'></div>
</div>
Post a Comment for "How To Count The Number Of Elements On The First Row Of Their Parent Element"