Reputation: 21
I need to switch two image with .click event on the same image, with callback function on 1° image and 2° image.
my purpose is to create an simple audio player for my site with only mute/unmute function by click image.
i have "icontrue.png" and "iconfalse.png".
The CSS on "iconfalse.png" is set on "display:none"
this is the html:
<img src="http://www.gastronomiasanfilippo.it/img/icontrue.png" id="true" class="show" />
<img src="http://www.gastronomiasanfilippo.it/img/iconfalse.png" id="false" class="hide"/>
this is the css:
#false{
cursor:pointer;
}
#true{
cursor:pointer;
}
.show{display:inline;}
.hide{display:none;}
this is jquery:
$("#true").click(function(){
$(this).addClass("hide");
$("#false").css("display","inline");
});
with this code i can't switch image ever by click event and can't have callback function, what's the way for do this?
This is jfiddle: http://jsfiddle.net/b9ykmtLp/
Upvotes: 0
Views: 84
Reputation: 2520
Try this:
var muted = false;
$("#mute-unmute").click(function () {
muted = !muted;
if (muted) {
$(this).addClass("muted");
// mute(true);
} else {
$(this).removeClass("muted");
// mute(false);
}
});
#mute-unmute {
width: 50px;
height: 50px;
background-image: url("https://cdn1.iconfinder.com/data/icons/warnings-and-dangers/400/Warning-02-512.png");
cursor: pointer;
}
#mute-unmute.muted {
background-image: url("https://cdn2.iconfinder.com/data/icons/web-and-apps-interface/32/Cancel-512.png");
}
<div id="mute-unmute"></div>
demo: http://jsfiddle.net/b9ykmtLp/20/
Upvotes: 2
Reputation: 53
There are of course numerous different ways you can do this, but the most effective way I can think of is to use jQuery's toggle(); function - http://api.jquery.com/toggle/ this since it allows you to get rid of all unnecessary markup. At the top of my head, this is how I would do it:
Choose one of the images to be the default one and hide the other one. Then just wrap both of them in a parent div, give that div a semantic name, reference it with jquery and use toggle(); to toggle the visibility of it's content when clicked. Short and simple:
HTML:
<div id="button">
<img src="http://www.gastronomiasanfilippo.it/img/icontrue.png" class="default" />
<img src="http://www.gastronomiasanfilippo.it/img/iconfalse.png"/>
</div>
CSS:
#button img {
display: none;
}
#button img.default {
display: block;
}
jQuery:
$('#button').on('click', function(){
$(this).find('img').toggle();
});
Here's a working fiddle:
http://jsfiddle.net/b9ykmtLp/13/
Upvotes: 0
Reputation: 6013
You can use jQuery's .show()
and .hide()
and just repeat your code for the other image (#false
).
jsFiddle: http://jsfiddle.net/b9ykmtLp/16/
$("#true").click(function(){
$(this).hide();
$("#false").show();
});
$("#false").click(function(){
$(this).hide();
$("#true").show();
});
Upvotes: 1