Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide particular div onload and then show div after click

Tags:

html

jquery

click

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>
like image 823
swapnesh Avatar asked May 30 '12 05:05

swapnesh


People also ask

How do I hide a div and then show on click?

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 .

How do I hide a div when a page is loaded?

Use display none on the element eighter in HTML, or in CSS files.

How do I hide a specific div?

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.


2 Answers

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/

like image 147
Sampson Avatar answered Oct 20 '22 09:10

Sampson


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>
  • If you want the div to be hidden on load, make the style display:none
  • Use toggle rather than click function.


Links:

JQuery Tutorials

  • 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)

JQuery References

  • http://api.jquery.com/
  • http://oscarotero.com/jquery/
like image 36
Dom Avatar answered Oct 20 '22 10:10

Dom