-2

I have a news page which (for the sake of length) uses a Show/Hide script for long contents. Thing is that the script is applied globally to all the contents and I would like it to be applied to only one element or to the nearest element.

Script:

$(document).ready(function(){ 

   $(".btn1").click(function(){
      $("p.esl").hide();
   }); 

   $(".btn2").click(function(){
      $("p.esl").show();

   });
});

Website: http://thc-racing.com/

P.S. I'm new to jQuery so my skill are very limited.

Skan So
  • 153
  • 1
  • 3
  • 15
  • 1
    Nearest to what? You should probably add some HTML as well, and explain the isse a little better ! – adeneo Dec 26 '14 at 13:00
  • Use `id` for 1 element not `class`. – CnapoB Dec 26 '14 at 13:01
  • Use any transversal method to target specific element regarding specific clicked element using `this` in click handler. Now you have to post relevant HTML markup in question itself. This is completly useless for futur readers to only post link to any thirs party website. What if your HTML markup site changes??? – A. Wolff Dec 26 '14 at 13:01
  • Try to calculate number of character then apply show and hide content – Hardik Raval Dec 26 '14 at 13:03
  • check when the height of the article is longer as the value you want. when longer hide, when nog don't hide. – Vinc199789 Dec 26 '14 at 13:03
  • @adeneo Nearest to the button which was clicked to Show/Hide. – Skan So Dec 26 '14 at 13:23

3 Answers3

2

This following code will fix your problem.

$(document).ready(function(){ 

   $(".btn1").click(function(){
      $(this).parents(".news-item").find(".esl").hide();
   }); 

   $(".btn2").click(function(){
      $(this).parents(".news-item").find("p.esl").show();
   });
});

this code will not hide all the p tags which only hide belongs to news item cheers

Naveen Setty
  • 615
  • 5
  • 26
1

Use id not the class

$(document).ready(function(){ 

   $("#btn1").click(function(){
      $("p#esl1").hide();
   }); 

   $("#btn2").click(function(){
      $("p#esl1").show();

   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id = "esl1">Here is my paragraph!!!! Hi I can hide</p>
<p id = "esl2">Here is my paragraph!!!! Hi I won`t hide</p>
<button id = "btn1">hide</button>
<button id = "btn2">show</button>

May be this answer here, will help you understand more.

Community
  • 1
  • 1
Hitesh
  • 4,098
  • 11
  • 44
  • 82
1

As @naveen said above is best way to deal with this kind of scenarios

$(document).ready(function(){ 

   $(".btn1").click(function(){
      $(this).parents(".news-item").find(".esl").hide();
   }); 

   $(".btn2").click(function(){
      $(this).parents(".news-item").find("p.esl").show();
   });
});

in this logic traversing to its part and finding its own child will solve event click problem.

Vikky
  • 33
  • 4