I want to know the simplest way to toggle the .fadeTo()
effect when someone click again on Click Me!
button then it will reverse the process again. I mean just like the .fadeToggle()
works or something like that. But using .fadeToggle()
cause the div to disappear.
Here is my - JSFiddle
HTML
<button>Click Me!</button>
<div></div>
CSS
div {
background-color: #ff0000;
width: 200px;
height: 200px;
margin: 20px
}
jQuery
$(document).ready(function(){
$("button").click(function(){
$("div").fadeTo(400,0.4);
});
});
I want to know the simplest way to toggle the .fadeTo()
effect when someone click again on Click Me!
button then it will reverse the process again. I mean just like the .fadeToggle()
works or something like that. But using .fadeToggle()
cause the div to disappear.
Here is my - JSFiddle
HTML
<button>Click Me!</button>
<div></div>
CSS
div {
background-color: #ff0000;
width: 200px;
height: 200px;
margin: 20px
}
jQuery
$(document).ready(function(){
$("button").click(function(){
$("div").fadeTo(400,0.4);
});
});
Share
Improve this question
asked Apr 23, 2014 at 13:33
AnonymousAnonymous
10.2k3 gold badges26 silver badges39 bronze badges
2 Answers
Reset to default 7You could use following snippet:
DEMO
$(document).ready(function () {
$("button").click(function () {
this.toggle = !this.toggle;
$("div").stop().fadeTo(400, this.toggle ? 0.4 : 1);
});
});
Or usually better solution is to toggle a class instead:
DEMO
CSS:
div {
background-color: #ff0000;
width: 200px;
height: 200px;
margin: 20px;
-webkit-transition: opacity 400ms linear;
transition: opacity 400ms linear;
}
div.faded {
opacity:.4;
}
jQuery:
$(document).ready(function () {
$("button").click(function () {
$("div").toggleClass('faded');
});
});
Much simpler ,
<button>fadeToggle p1</button>
<p>This paragraph has a slow, linear fade.</p>
<script>
$( "button:first" ).click(function() {
$( "p:first" ).fadeToggle( "slow", "linear" );
});
</script>