-1

I have an html page and I want to show and hide content on button click.

HTML:

<div class="wpb_wrapper">

  <p>
    <button class="learn-more">Learn More</button>
    <button class="learn-more">Learn More</button>
    <button class="learn-more">Learn More</button>
    <button class="learn-more">Learn More</button>
 </p>

<p class="hide_paragraph" id="p1" style="display: none;">First paragraph</p>
<p class="hide_paragraph" id="p2" style="display: none;">Second paragraph</p>
<p class="hide_paragraph" id="p3" style="display: none;">Third paragraph</p>
<p class="hide_paragraph" id="p4" style="display: none;">Fourth paragraph</p>

        </div>

Also my function

$(document).ready(function () {
$('.wpb_wrapper p .learn-more').click(function(){

    $('.wpb_wrapper p .hide_paragraph').hide();
    $('#' + $(this).attr('paragraph_id')).show();

});

});

But it doesn't work

1
  • $(this).attr('paragraph_id')).show(); no such thing Commented Nov 27, 2015 at 0:00

2 Answers 2

5

There is no attribute called paragraph_id in your button tags, so your $(this).attr('paragraph_id') returns undefined. Since paragraph_id is not a standard HTML attribute, I advise against simply adding it. Instead just add to each button a data-attribute like so:

<button class="learn-more" data-paragraph-id="#p1">Learn More</button>

and in your handler use $(this).data('paragraph-id') to identify the paragraph to be shown.

Notice that the hash sign is included so you don't have to use the string concatenation anymore. Simply call:

$($(this).data('paragraph-id')).show();
3
  • Now I have $(document).ready(function () { $('.learn-more').click(function(){ $('.hide_paragraph').hide(); $((this).data('paragraph-id')).show(); }); }); But it doesnt work Commented Nov 27, 2015 at 0:11
  • 1
    @ВасяПупкин You forgot the $ before the (this). Commented Nov 27, 2015 at 0:20
  • 1
    This one should be the answer +1 - here is the demo jsfiddle.net/1njuL4xr
    – Cory
    Commented Nov 27, 2015 at 0:24
0
$(document).ready(function () {
 $('elem').click(function(){
  var getIndex = $('elem').index(this);
  $('elem2').hide();
  $('elem2:eq"' + getIndex + '"').show();
 });
});

Should work, hope it is exactly what you want :)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.