user1469270
user1469270

Reputation:

Simple .is() not working as expected

I'm trying to loop through images, and if the last image has a class of .active, I start again. However, it is not working at all:

http://jsfiddle.net/tmyie/VE75U/

img.click(function () {
    $(this).removeClass('active').next('img').addClass('active');
    if ($('.active').is(':last-child')) {  
       img.first().addClass('active');
    }

});

Upvotes: 0

Views: 39

Answers (2)

Tony
Tony

Reputation: 7445

You have 2 issues in your code:

When you click on last image this code:

$(this).removeClass('active').next('img').addClass('active');

Will not add active class to anything, because .next('img') will return an empty array. So next line will not work too:

if ($('.active').is(':last-child'))

Because there is no active elements.

I believe you need to fix it in the following way:

if ($(this).is(':last-child'))

Next thing: none of your images can be a :last-child, because even your last image is not a last child! Look carefully at your html code:

<div class="module m-slide">
    <img src="http://placehold.it/1200x800&text=1" alt="" />
    <img src="http://placehold.it/1200x800&text=2" alt="" />
    <img src="http://placehold.it/1200x800&text=3" alt="" />
    <div class="m-slide-ctrl"></div>
</div>

Your last child is <div class="m-slide-ctrl"></div>

I suggest to change it in the follosing way:

<div class="module m-slide">
    <div class="m-slide-ctrl"></div>
    <img src="http://placehold.it/1200x800&text=1" alt="" />
    <img src="http://placehold.it/1200x800&text=2" alt="" />
    <img src="http://placehold.it/1200x800&text=3" alt="" />
</div>

Demo

Upvotes: 0

adeneo
adeneo

Reputation: 318242

To check if the last image has the class .active you have to almost reverse it and first get the last image and then check for the class, and since the last-child isn't an image, that wont work

if ( $('.module.m-slide img:last').hasClass('.active') ) { ...

Upvotes: 1

Related Questions