Rohan Patil
Rohan Patil

Reputation: 1963

Jquery Select only one Image from list

Want to select only one image at a time from this below jsbin link code

http://jsbin.com/avaxay/1/edit

Code:

$(function() {

  $("img").click(function() {

    $("img").not(this).removeClass("hover");

    $(this).toggleClass("hover");

  });

  $("#btn").click(function() {

    var imgs = $("img.hover").length;    
    alert('there are ' + imgs + ' images selected');

  });

});

Thanks....

Upvotes: 0

Views: 1851

Answers (4)

gmo
gmo

Reputation: 9000

You could use jQuery.one() function or jQuery.off()

I think the best solution here could be the use of jQuery.off('click')

$("img").click(function(){
   $("img").off('click');
});

and then, re-enable when the alert is triggered

Example: http://jsfiddle.net/c7puz/

JS

// function to do something when the click is trigger
function enableSelect(){
    $("img").click(function(){
      $(this).toggleClass("hover");
      // toggle off the click, so only first one will work,
      // until the function is called again
      $("img").off('click');
    });
}enableSelect();

$("#btn").click(function(){
    var pos = $("img.hover").parent().index();
    if(pos > -1){
        // tell us the selected image to work with
        alert('The selected image is at position: ' + pos );
        // clear the hover state
        $("img").removeClass("hover");
        // and enable the click again
        enableSelect();
    } else {
        alert('no image selected');
    }
});

Good luck ;-)

Upvotes: 0

Irvin Dominin
Irvin Dominin

Reputation: 30993

You can use the following code:

  $("img").click(function() {

    $("img").not(this).removeClass("hover");

    $(this).toggleClass("hover");

  });

it removes the hover class from all images (except the current removed with the not method) and toggle the class for the current.

Updated jsbin: http://jsbin.com/avaxay/36/edit

Upvotes: 3

Doan Cuong
Doan Cuong

Reputation: 2624

$("img").click(function() {
    $("img.hover").attr('class', '');
    $(this).toggleClass("hover");

  });

I hope this is what you expected

Upvotes: 1

slash197
slash197

Reputation: 9034

  $("img").click(function() {

    $('ul > li > img').removeClass("hover);
    $(this).addClass("hover");

  });

Upvotes: 1

Related Questions