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 mad
$(document).ready(function() {
$('#div2').hide(0);
$('#preview').on('click', function() {
$('#div1').hide(300, function() { // first hide div1
// then show div2
$('#div2').show(300);
});
});
});
You missed #
before div2
Working Sample
The second time you're referring to div2, you're not using the # id selector.
There's no element named div2.
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/
You are missing #
hash character before id selectors, this should work:
$(document).ready(function() {
$("#div2").hide();
$("#preview").click(function() {
$("#div1").hide();
$("#div2").show();
});
});
Learn More about jQuery ID Selectors
At first if you want to hide div element with id = "abc" on load and then toggle between hide and show using a button with id = "btn" then,
$(document).ready(function() {
$("#abc").hide();
$("#btn").click(function() {
$("#abc").toggle();
});
});
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)