Reputation: 13
I want to create an event with Javascript onclick
that will enable the clicked image and will disable others.
For example, if I have 6 pictures, how can I do the following: I want to click any picture for example picture number 3, then picture number 3 will be enabled and the pictures 1,2,4,5,6 will be disabled.
A few seconds after, I want to click on picture number 1, then it will become active and 2,3,4,5,6 will be disabled.
How can I do this?
Upvotes: 0
Views: 1186
Reputation: 199
You can do this using jQuery Siblings
Here an example:
$(function(){
$("img").click(function(){
$(this).addClass("on").siblings("img").removeClass("on");
});
});
Edit, working example:
$(function(){
var replaceImg = function($img){
var src0= $img.attr("src");
var src1= $img.data("on-src");
$img.attr("src",src1).data("on-src",src0);
};
$("img").click(function(){
$(this).addClass("on");
replaceImg($(this));
$(this).siblings("img").each(
function(){
var $this = $(this);
if($this.hasClass("on")){
$(this).removeClass("on");
replaceImg($(this));
}
}
);
});
});
img{border:solid 3px black;}
img.on{border:solid 3px red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<img src="https://67.media.tumblr.com/avatar_0c16e55c511b_128.png" data-on-src="http://icons.iconarchive.com/icons/jonathan-rey/simpsons/128/Homer-Simpson-04-Happy-icon.png">
<img src="https://67.media.tumblr.com/avatar_0c16e55c511b_128.png" data-on-src="http://icons.iconarchive.com/icons/jonathan-rey/simpsons/128/Homer-Simpson-04-Happy-icon.png">
<img src="https://67.media.tumblr.com/avatar_0c16e55c511b_128.png" data-on-src="http://icons.iconarchive.com/icons/jonathan-rey/simpsons/128/Homer-Simpson-04-Happy-icon.png">
<img src="https://67.media.tumblr.com/avatar_0c16e55c511b_128.png" data-on-src="http://icons.iconarchive.com/icons/jonathan-rey/simpsons/128/Homer-Simpson-04-Happy-icon.png">
<img src="https://67.media.tumblr.com/avatar_0c16e55c511b_128.png" data-on-src="http://icons.iconarchive.com/icons/jonathan-rey/simpsons/128/Homer-Simpson-04-Happy-icon.png">
</div>
Edit 2 - For Change the image
Upvotes: 1