Reputation: 23
I'm looking to change the color of the button or in this case the image of the button each time the button is selected on the toggle of the jQuery. Here's what I have so far for jQuery.
jQuery(document).ready(function () {
jQuery('#occupation').hide();
jQuery('#occupationshow').on('click', function (event) {
jQuery('#occupation').toggle();
});
});
And here's what I have for the button:
<button id="occupationshow">
<img src="../SiteAssets/images/RAC/askcut/Occupation.jpg">
</button>
How can I get it so another image is displayed on the button when the button has been clicked?
Upvotes: 0
Views: 158
Reputation: 712
The best way to do this is I think the following:
background-image
of the element using CSSbutton#occupationshow
a fixed width/height, have the jquery modify the background-position
of the image depending on the state of the button - simply put, depending on the current state of the button, the image will move left/right within button#occupationshow
and you will only be able to see the relevant part at any one time.You can as suggested modify the src
attribute dynamically, but do bear in mind that with this approach the new image might take a moment to load once the button is clicked; with my approach both images are preloaded (as they are one image) and it's simply moving around, and so is instant.
Sprites are a great way of working, I'd recommend looking into them :-)
Upvotes: 1
Reputation:
I guess you only have two images, right? So what you can do is put two tags, corresponding to both of your images, ont being set as "display: none".
<button id="occupationshow">
<img src="../img1.jpg">
<img src="../img2.jpg" style="display: none;">
</button>
And in jQuery your code will be :
jQuery('#occupationshow').on('click', function (e) {
jQuery('#occupationshow img').toggle();
});
Edit: I re-read the first post again and don't know what made me guess OP only had two images... (the fact he wants to use "toggle", I guess)
Upvotes: 0
Reputation: 30557
toggle()
by default is for showing/hiding. Use attr() with a callback function
jQuery('#occupationshow').on('click', function (event) {
jQuery(this).find('img').attr('src', function(){
var src = $(this).attr('src') == 'img1' ? 'img2' : 'img1';
return src;
});
});
Upvotes: 0
Reputation: 822
You can use the css function of jquery to change the background image of a button on every click.
Upvotes: 0