Reputation: 1963
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
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/
// 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
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
Reputation: 2624
$("img").click(function() {
$("img.hover").attr('class', '');
$(this).toggleClass("hover");
});
I hope this is what you expected
Upvotes: 1
Reputation: 9034
$("img").click(function() {
$('ul > li > img').removeClass("hover);
$(this).addClass("hover");
});
Upvotes: 1