0

I am trying to make an app in which when you click some text it shows content and when you click again it hides it. my current jquery is this:

$(document).ready(function(e) {

$("h2").toggle( 
    function(){ $(this).next().show(); },
    function(){ $(this).next().hide(); }
    ); //end of toggle

}); // end of ready

but when I run it on browser everything hides immediately

2 Answers2

0

You should use the .click() function instead, toggle is used to switch visibility on/off

"With no parameters, the .toggle() method simply toggles the visibility of elements" (link to doc).

And you don't really need the $(document.ready) unless you are loading scripts after the </body> tag (see this question)

$("h2").click( function(){ 
   $(this).next().toggle(); 
});

EDIT : Depending on your jQuery version, behaviour might change

EDIT 2 : to start hidden, just add

$("h2").next().hide(); 

Or give it a class/id, and in your CSS stylesheet add

#yourId {
    visiblity: hidden;
}
Community
  • 1
  • 1
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164
  • Thank you very much,is there a way I can make it start as hidden? –  Sep 17 '14 at 21:31
  • I am using jquery 1.11.1, toggle(false); doesn't work,I'll go with css,thanks for all that info,I'll choose your answer when possible. –  Sep 17 '14 at 21:36
  • Sorry, i edited it just after to replace by "hide()", which is what you originally did ^^" – Cyril Duchon-Doris Sep 17 '14 at 21:36
0

You can use .click() to add an onclick handler to your <h2>, which toggles the display of the next element. Try this code:

$(document).ready(function() {
    $("h2").click(function(){ 
        $(this).next().toggle();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Clickable Title</h2>
<p>Toggle text</p>
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141