JQuery: Click to show hide individual paragraphs

I am trying to create a site that will have a summary paragraph with the option to extend for more info on click. I have done this with this code.

$(document).ready(function() {
$("#here").hide();
$("#show").click(function() {
    $("#here").show();
    $("#icond").hide();
});

$("#hide").click(function() {
    $("#here").hide();
    $("#icond").show();
});

My issue is that I want to be able to do this a number of times throughout the page with different div/p elements.

When I attempted to do this with classes it would open/close all at the same time. The only solution I know of is to retype the function for each id.

Is there another way?

Thanks in advance!

https://jsfiddle.net/58roy7hg/

Answers 1

  • You would have to use the this keyword and then use tree traversal to target particular elements you want to show and hide as the answer above suggests. Some additional tips I would give you are:

    1. Avoid using document.ready multiple times.
    2. I would suggest using .on instead of .click, as it is more versatile, allowing you to drill-down to dynamically added elements.
    3. Avoid using id too much; this is to be used for elements that are not repeated throughout the page (e.g. navigation bar). Most of your id can be replaced with class.

    Try out this sample: jsfiddle

    I just quickly made a sample (with my own markup) to show you, so you can re-purpose it as you wish, but I would definitely recommend checking out the documentation to gain a feel.


Related Articles