Reputation: 757
Let say I have 4 images in a form:
<form>
<img class="image" src="/imge1.jpg"/>
<img class="image" src="/imge2.jpg"/>
<img class="image" src="/imge3.jpg"/>
<img class="image" src="/imge4.jpg"/>
</form>
If I click 1 images is it possible to know the count of images right to the clicked image and count of images left to clicked image?
For example if I clicked image 2, I should get left=1 right=2 for image 3 right=1 left=2.
Upvotes: 0
Views: 85
Reputation: 2523
Try with prevAll() and nextAll() for the clicked element as shown in the snippet.
$(".image").on("click", function(e){
console.log("Left: " + $(this).prevAll("img").length);
console.log("Right: " + $(this).nextAll("img").length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>Whats this? A parapgraph?!</p>
<img class="image" src="/imge1.jpg"/>
<img class="image" src="/imge2.jpg"/>
<img class="image" src="/imge3.jpg"/>
<img class="image" src="/imge4.jpg"/>
</form>
Upvotes: 3
Reputation: 2000
check,
$('.image').click(function(){
var left = $(this).prevAll().length -1;
var right = $(this).nextAll().length -2;
alert("On your left : " + left + " on your right: " + right);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<img class="image" src="/imge1.jpg"/>
<img class="image" src="/imge2.jpg"/>
<img class="image" src="/imge3.jpg"/>
<img class="image" src="/imge4.jpg"/>
Upvotes: 0
Reputation: 12880
You could simply combine the use of .index()
and the length of the parent's img
children :
$(this).index()
will give you the number of img
to the left of the one clicked.
$(this).parent().children('img').length - $(this).index() - 1
will give your the number of img
to the right of the one clicked.
$('img').on('click',function(){
console.log('There are '+($(this).index())+' cat(s) to the left');
console.log('There are '+($(this).parent().children('img').length - $(this).index() - 1)+' cat(s) to the right');
});
img{
width: 50px;
height: 50px;
object-fit: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<img class="image" src="http://www.catster.com/wp-content/uploads/2017/08/A-fluffy-cat-looking-funny-surprised-or-concerned.jpg" />
<img class="image" src="https://upload.wikimedia.org/wikipedia/commons/3/3a/Cat03.jpg" />
<img class="image" src="http://www.catster.com/wp-content/uploads/2017/06/small-kitten-meowing.jpg" />
<img class="image" src="https://www.petmd.com/sites/default/files/petmd-cat-happy.jpg" />
</form>
Upvotes: 1
Reputation: 1071
You can use jquery prevAll(); and nextAll();
$('.image').click(function){
console.log($.prevAll('.image').length);
console.log($.nextAll('.image').length);
});
Upvotes: 0