I have a list of divs with images in them:
<div class="wizard-img"><%= image_tag("sources/pix/nyt.png") %></div>
<div class="wizard-img"><%= image_tag("sources/pix/theguardian.png") %></div>
When a user clicks the div, I'd like it to change the image to x-on.png, when clicked again, it'll change to x-off.png, and when clicked a third time it should revert to x.png.
Is it possible to do this without manually specifying jQuery for every image change? Can I traverse the div and find the image name, and simply append the -off/-on to the image?
Thanks!
You can use the . toggle() function.
The slideToggle() method toggles between slideUp() and slideDown() for the selected elements. This method checks the selected elements for visibility. slideDown() is run if an element is hidden. slideUp() is run if an element is visible - This creates a toggle effect.
jQuery toggle() Methodshow() is run if an element is hidden. hide() is run if an element is visible - This creates a toggle effect. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: This method can also be used to toggle between custom functions.
Perhaps CSS sprites would work for you?
That would save you from loading a separate image every time you click the image (button?), and you could solve your problem by adding and removing a css-class, e.g.:
$('.wizard-img').click(
function() {
if ($(this).hasClass('on')) {
$(this).removeClass('on').addClass('off');
} else if ($(this).hasClass('off')) {
$(this).removeClass('off');
} else {
$(this).addClass('on');
}
}
);
http://docs.jquery.com/Events/toggle
$(".wizard-img").toggle(
function () {
$(this).find("img").attr({src:"x-on.png"});
},
function () {
$(this).find("img").attr({src:"x-off.png"});
},
function () {
$(this).find("img").attr({src:"x.png"});
}
);
CSS Sprites would indeed be the way to do this, but just for completeness, here's another option.
Normally I'm the last to reach for a regexp, but I think they'll help here
$('.wizard-img').click(function() {
var $img = $(this).find('img') ,
src = $img.attr('src') ,
onCheck = /\-on\.jpg$/ ,
offCheck = /\-off\.jpg$/ ,
normal = /\.jpg$/
;
if(src.match(onCheck)) {
$img.attr('src', src.replace(onCheck, '-off.jpg'));
} else if (src.match(offCheck)) {
$img.attr('src', src.replace(offCheck, '.jpg'));
} else {
$img.attr('src', src.replace(normal, '-on.jpg'));
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With