JQuery: click to hide the DIV, how can I make one function to click and hide individual divs?

I have several sections as shown below. I want 1 (one) jQuery function that disables ahref (.hide), hide data inside <div class="data"> .
1. This should be 1 function that can hide multiple divs
2. The explanation would be great when using the jquery this selector, I suspect this is what I need.
3. Keep it simple!
4. Also a good slide switch effect will be great to slide up and down on click.

I tried to do this, but I had to make a different jquery code for each div, which is ... long ..
Thanks for any help !! and hopefully the correct answers!

 <div id="uniqueDiv1" class="frame"> <a href="#" class="hide">Hide</a> // On click of this Div <div class="data"> <pre>data</pre> // Hide This Div or Data </pre> </div> <div id="uniqueDiv2" class="frame"> <a href="#" class="hide">Hide</a> // On click of this Div <div class="data"> <pre>data</pre> // Hide This Div or Data </pre> </div> <remember> I want 1 simple Jquery DOM function for all Multiple Divs </remember> 
+6
source share
4 answers

You could do this:

 $('div.frame a.hide').click(function(e){ e.preventDefault(); $(this).next('div.data').toggle(); }); 

http://jsfiddle.net/niklasvh/QbDMs/

  • $('div.frame a.hide') selects all hide links.
  • e.preventDefault(); prevents default link action
  • $(this).next('div.data').toggle(); selects the next div with class="data" and switches its visibility

edit - you did not mention this, but if you want to also switch the text on the button, you can add:

 if ($(this).text()=='Show'){ $(this).text('Hide'); }else{ $(this).text('Show'); } 

make the final code look like this:

 $('div.frame a.hide').click(function(e){ e.preventDefault(); var div =$(this).next('div.data').slideToggle(); if ($(this).text()=='Show'){ $(this).text('Hide'); }else{ $(this).text('Show'); } }); 
+4
source
 $("a.hide").click(function(){ $(this).parent().find(".data").slideToggle(); }); 

That should work. this refers to the item clicked. It just finds .data inside the parent div and slideToggle it.

script: http://jsfiddle.net/yJfbP/

NOTE. Your html in your post is incorrect. You have a </pre> where you should end the div.

+4
source
 $(document).ready(function(){ $('.hide').click(function()) { $(this).next().hide(); }); }); 
+1
source

Try the following:

 $(".frame .hide").click(function(){ var $this = $(this); var txt = $this.text(); if(txt == "Hide"){ $this.text("Show"); } else { $this.text("Hide"); } $this.next(".data").toggle(); }); 
+1
source

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


All Articles