Add add/remove class click picture in queue jQuery

664 views Asked by At

I have those pictures

<img src=img1.jpg class=pic />
<img src=img2.jpg class=pic />
<img src=img3.jpg class=pic />
<img src=img4.jpg class=pic />
<img src=img5.jpg class=pic />
<img src=img6.jpg class=pic />

.ShowBorderRed{border:3px solid red;}

I want to add the class .ShowBorderRed once I click one of them and remove this class once I click another picture and add the class to this new image. JQuery

3

There are 3 answers

0
Derek Foulk On BEST ANSWER

Use the following:

$(document).ready(function(){
    var $img = $('.pic');
    $img.click(function(event){
        $img.removeClass('ShowBorderRed');
        $(this).addClass('ShowBorderRed');
    });
});
0
Appu On
Use the following code:

$(document).ready(function(){
    var $img = $('.pic');
    $img.click(function(event){
        $img.removeClass('ShowBorderRed');
        $(this).addClass('ShowBorderRed');
    });
});
refer the below mentioned link.
http://jsfiddle.net/2QyY3/199/
1
Tushar On

See the comments inline in the code:

// bind click event on all the images having pic class
$('img.pic').on('click', function() {
    $(this).addClass('ShowBorderRed') // Add class to the clicked image
        .siblings().removeClass('ShowBorderRed'); // Remove class from other sibling images
});

DEMO

OR

If the images are not siblings:

var $images = $('img.pic');
$images.on('click', function() {
    $images.removeClass('ShowBorderRed'); // Remove class from all other images
    $(this).addClass('ShowBorderRed'); // Add class to the clicked image
});

DEMO