addClass should only apply to the next IMG
-
27-10-2019 - |
Question
I hope somebody can help me. how can I make addClass applies only to the next img and not to all following? edit: the "addClass" should always apply to the next following IMG so that you can click through all images one after an other - like a gallery
$("#next").click(function(){
if($("#gallery li").next("#gallery li").length != 0) {
$("#gallery li").children("img").removeClass('toppicture');
$("#gallery li").next("#gallery li").children("img").addClass('toppicture');
}
else {
$(this).children("img").removeClass('toppicture');
$("#gallery li:first-child").children("img").addClass('toppicture');
}
});
the ul with the id "gallery" looks like this :
<li>
<img class="toppicture" src="images/w1.jpg" title="Title #0"/>
</li>
<li>
<img src="images/w2.jpg" title="Title #1"/>
</li>
<li>
<img src="images/w3.jpg" title="Title #2"/>
</li>
Solution
Have you tried :
$("#next").click(function(){
if($("#gallery li").next("#gallery li").length != 0) {
var obj = $(".toppicture").parent("li").next().children("img");
$("#gallery li").children("img").removeClass('toppicture');
$(obj).addClass('toppicture');
}
else {
$(this).children("img").removeClass('toppicture');
$("#gallery li:first-child").children("img").addClass('toppicture');
}
});
OTHER TIPS
Maybe you could try
$("#next").click(function(){
//find the li with the class
var liTop = $("#gallery li.toppicture");
//if it has another element remove the class from itself and add it to the next
if(liTop.next().length !== 0) {
liTop.removeClass('toppicture');
liTop.next().addClass('toppicture');
}
else {
$(this).children("img").removeClass('toppicture');
$("#gallery li:first-child").children("img").addClass('toppicture');
}
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow