I am trying to learn jquery and I have 2 div elements that I want only with one button to toggle between hide and show. I tried to write everything that I want but I think the sintax is wrong.
<div id="first"></div>
<div id="second">
</div>
<button class="change">change</button>
CSS:
#first {
width:500px;
height:500px;
margin:0 auto;
background-color:#ccc;
}
#second {
width:500px;
height:500px;
margin:0 auto;
background-color:black;
display:none;
}
and I wrote as Jquery
$(document).ready(function() {
$('.change').click(function() {
$('#first').hide();
$('#second').show();
});
});
I was thinking about an if else statement however I am not sure if can handle that yet.
You can use toggle method of jQuery. Make your second div hidden on initialisation...
$(document).ready(function() { $('.change').click(function() { $('#first, #second').toggle(); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="first">first</div> <div id="second" style="display: none;">second</div> <button class="change">change</button>
working example: https://jsfiddle.net/tanaydin/kjyq0eow/3/
documentation: http://api.jquery.com/toggle/
edited after: @Darren Sweeney's comment, much better with this selector.
First thing, you won't see emptys divs.
Example - 1
$(document).ready(function() { $('.change').click(function() { $('#first').toggle(); $('#second').toggle(); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="first" style="display: none">teste</div> <div id="second">teste2</div> <button class="change">change</button>
Example - 2 You can check if a element is visible with that:
$(document).ready(function() { $('.change').click(function() { if($('#first').is(":visible")){ $('#first').hide(); $('#second').show(); }else{ $('#first').show(); $('#second').hide(); } }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="first">test1</div> <div id="second">test2</div> <button class="change">change</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.