Reputation: 628
I have the following code that, superbly, changes my image name from image_off.jpg to image_on.jpg on hover. I am using it for a gallery.
$(function(){
$(".img-swap").hover(
function(){this.src = this.src.replace("_off","_on");},
function(){this.src = this.src.replace("_on","_off");
});
});
However I want the image name to stay on image_on.jpg when I click one of the images. Is this possible and is it possible to have it swap back to off when I click another?
Thanks
Upvotes: 1
Views: 730
Reputation: 660
Hope this helps
it will work fine as you want with hover on and off and when you click the img it will be selected and will stay there and hover affect will not work
and when you click the next img all the rest which are selected will be removed and the hover affect will work on that
EDIT ** Changed the code Try it now
$(function(){
$(".img-swap").hover(
function(){
if(!$(this).hasClass("selected")) {
this.src = this.src.replace("_off","_on");
}
},
function(){
if(!$(this).hasClass("selected")) {
this.src = this.src.replace("_on","_off");
}
}).click(function(){
$('.img-swap').removeClass('selected').attr('src',this.src.replace("_on","_off"));;
this.src = this.src.replace("_off","_on");
$(this).addClass("selected").attr('src',this.src.replace("_off","_on"));
});
});
Upvotes: 2
Reputation: 28
You can just simply add css hover event for class if you can
.img-swap:hover { src: image_on.jpg }
Upvotes: 0
Reputation: 650
Here's some (untested) code:
$(function(){
$(".img-swap").hover(
function(){
this.src = this.src.replace("_off","_on");
},
function(){
if(!this.hasClass("selected")) {
this.src = this.src.replace("_on","_off");
}
}).click(function() {
$(".img-swap.selected").removeClass("selected");
this.addClass("selected");
});
});
What it's doing is adding a .selected
class to each clicked element. The hover-out function checks this class, and only does the replacement if the image is not selected.
Upvotes: 0
Reputation: 382092
You may use toggle instead of hover :
$(".img-swap").toggle(
function(){this.src = this.src.replace("_off","_on");},
function(){this.src = this.src.replace("_on","_off");
});
EDIT : to pin the image on click (prevent it to change back to off), you may do this :
$(".img-swap").hover(
function(){this.src = this.src.replace("_off","_on");},
function(){if (!pinned) this.src = this.src.replace("_on","_off");
}).click(){
$(this).data('pinned': !($(this).data('pinned')||false));
});
Upvotes: 1