Expand <p> when you press <h1>

I want to make a very simple extension / crash using JavaScript, where when I click "Title" it shows "Text" (which is hidden when the page loads first). Also, when I click on β€œTitle” again, I want the β€œText” to be hidden again.

<div> <h1>Title</h1> <p>Text</p> </div> 

I never used jQuery or JavaScript, so it would be great if you could explain a little how this switching code works. Thanks.

+1
source share
4 answers

Well, this should do it:

 $(function() { $('h1').click(function() { $(this).next('p').toggle(); }); }); 

Now let me explain the code.

The first line accepts a function that will be run after the document has finished loading. This is equivalent to:

 $(document).ready(function() { // Stuff to do when the document is ready. }); 

The code in the middle says that for each h1 element, when it is pressed, execute a function that will find the p element next to it and switch its visibility. this in the first selector refers to the actual <h1> DOM element. I did it this way, so if you had a structure like the following, then switching will only affect the content next to the paragraphs.

 <div> <h1>Section 1</h1> <p>Section 1 Content</p> </div> <div> <h1>Section 2</h1> <p>Section 2 Content</p> </div> 

Hurrah!

+6
source

Use toggle .

 $('h1').bind('click', function(){ $('p').toggle(); }); 
+1
source

Demo

 <head> <!-- other content, including jQuery script tag --> <script type="text/javascript"> $(function(){ // trigger when document ready // hide the pragraph initially $('p').hide(); // add a click event to the header so we can hide/show the paragraph $('h1').click(function(e){ // $(this) is the header, next finds the next paragraph sibling (they're both // withint he div, so the header and div are known as siblings) then toggle // toggles if this found paragraph should be shown or hidden $(this).next('p').toggle(); }); }); </script> </head> 

By clicking on the DIV, instruct jQuery to find the "next" element that paragraph (since the heading and paragraph are siblings of the same node), then toggle it.

I also added hide to the code, since, in my opinion, it is best to hide the content from javascript, so that if they do not support javascript, there is no missing content. Others use CSS styles and show only using javascript, and this is normal, but if they don’t have JS on or off on the page, there is no way to view this content again.

+1
source

try it

 $("h1").click(function(){ $("p").slideToggle(500); }); 
0
source

Source: https://habr.com/ru/post/925586/


All Articles