I have two divs div1
and div2
. I want div2 to be automatically hidden but when i click on preview
div then div2
to be made visible and div1
to hide. This is the code i tried but no luck :(
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("div2").hide();
$("#preview").click(function() {
$("#div1").hide();
$("#div2").show();
});
});
</script>
<div id="div1">
This is preview Div1. This is preview Div1.
</div>
<div id="div2">
This is preview Div2 to show after div 1 hides.
</div>
<div id="preview" style="color:#999999; font-size:14px">
PREVIEW
</div>
To display or hide a <div> by a <button> click, you can add the onclick event listener to the <button> element. The onclick listener for the button will have a function that will change the display attribute of the <div> from the default value (which is block ) to none .
Use display none on the element eighter in HTML, or in CSS files.
We hide the divs by adding a CSS class called hidden to the outer div called . text_container . This will trigger CSS to hide the inner div.
Make sure to watch your selectors. You appear to have forgotten the #
for div2
. Additionally, you can toggle the visibility of many elements at once with .toggle()
:
// Short-form of `document.ready`
$(function(){
$("#div2").hide();
$("#preview").on("click", function(){
$("#div1, #div2").toggle();
});
});
Demo: http://jsfiddle.net/dJg8N/
This is an easier way to do it. Hope this helps...
<script type="text/javascript">
$(document).ready(function () {
$("#preview").toggle(function() {
$("#div1").hide();
$("#div2").show();
}, function() {
$("#div1").show();
$("#div2").hide();
});
});
<div id="div1">
This is preview Div1. This is preview Div1.
</div>
<div id="div2" style="display:none;">
This is preview Div2 to show after div 1 hides.
</div>
<div id="preview" style="color:#999999; font-size:14px">
PREVIEW
</div>
Links:
http://docs.jquery.com/Main_Page
http://www.w3schools.com/jquery/default.asp (W3Schools)
http://thenewboston.org/list.php?cat=32 (Video Tutorials)
http://andreehansson.se/the-basics-of-jquery/ (Basic Tutorial)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With