Amir
Amir

Reputation: 537

Add and remove class onclick

I tried this code, but haven't had any chance to get it work. I want wehn i click on the image it get active class on it.

Here is my HTML

<ul id="og-grid">
    <li>
        <a href="#"><img src="http://hhhhold.com/150"></img></a>
    </li>

    <li>
        <a href="#"><img src="http://hhhhold.com/149"></img></a>
    </li>

    <li>
        <a href="#"><img src="http://hhhhold.com/151"></img></a>
    </li>
</ul>

and here is the jQuery

$(document).ready(function() {
    $('#og-grid li a').click(function (e) {
        e.preventDefault();
        $(this).closest('img').addClass('active').siblings().removeClass('active');

    });

});
});//]]> 

Has anybody done this before, so can help me out with?

JSFIDDLE

Upvotes: 0

Views: 743

Answers (3)

Samsquanch
Samsquanch

Reputation: 9146

I'd do it in two steps:

// clear active classes from all images
$('#og-grid li a img').removeClass('active');
// add active class to clicked image
$(this).find('img').addClass('active');

Fiddle.

Upvotes: 1

sbonkosky
sbonkosky

Reputation: 2557

Try this

JSFiddle

$(document).ready(function() {
    $('#og-grid li a').click(function (e) {
        e.preventDefault();
        $('#og-grid li a img').removeClass('active');
        $(this).find('img').addClass('active');
    });
});

Upvotes: 2

Leeish
Leeish

Reputation: 5213

Closest only goes up the DOM not down. Use Children. Additionally, the img has no siblings, it's the li elements that have siblings. So you'd need to go back up the DOM to fix those.

I would just remove all of the classes and then add the one you need.

Upvotes: 0

Related Questions