Reputation: 17
I need to make this line of code into an If/Else statement for a school project and cannot figure out how to do so. The button currently triggers the picture to show on the page, but I cannot figure out how to also make it hide on button click using an If/Else statement.
$('#showA').on('click', function() {
$('#house1').css('opacity', 1).fadeIn('slow');
});
Upvotes: 0
Views: 74
Reputation: 22500
No need a if/else - just use with fadeToggle()
of Jquery
function .
$('#showA').on('click', function() {
$('#house1').fadeToggle('slow');
});
Refer the Demo snippet
$('#showA').on('click', function() {
$('#house1').fadeToggle('slow');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="showA">show</p>
<h3 id="house1">hello</h3>
Use with if/else for OP required
fadeIn
and fadeOut
depend on count
variablecount
reset to 0
count == 0
element will be hiddenvar count=0;
$('#showA').on('click', function() {
if(count == 0){
$('#house1').fadeOut('400');
count++
}
else {
$('#house1').fadeIn('400');
count=0
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="showA">show</p>
<h3 id="house1">hello</h3>
Upvotes: 1
Reputation: 41893
There's a jQuery
function responsible for it - fadeToggle
.
Note: fade
function already operates the opacity
property, you don't need to include it.
$('#showA').on('click', function() {
$('#house1').fadeToggle('slow');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='showA'>click</button>
<p id='house1' hidden>Hi</p>
Upvotes: 0