Home > Software engineering >  when I click on Expand all div are expanded
when I click on Expand all div are expanded

Time:08-08

$(document).ready(function(){
  $('.toggle').click(function(){
    $('.text-hidden').slideToggle();
  });
});

This is the code click on expand div expand but why all the div having class text-hidden expand and how to use this keyword for text-hidden

CodePudding user response:

...but why all the div having class text-hidden expand...

Because that's what $('.text-hidden').slideToggle(); says to do: Find all elements with the class text-hidden and call slideToggle on them.

If you just want the ones within the div that was clicked, you have to tell jQuery that, for instance with the find method:

$(document).ready(function () {
    $(".toggle").click(function () {
        $(this).find(".text-hidden").slideToggle();
    });
});

Example:

$(document).ready(function () {
    $(".toggle").click(function () {
        $(this).find(".text-hidden").slideToggle();
    });
});
.text-hidden {
    display: none;
}
<div >
    <div>Always visible</div>
    <div >Hidden by default</div>
</div>

<div >
    <div>Always visible</div>
    <div >Hidden by default</div>
</div>

<div >
    <div>Always visible</div>
    <div >Hidden by default</div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Or if both .toggle and .text-hidden elements are in the same container, you might need to go up to that container first (via closest); in this example, I'll use the class container as a stand-in for whatever identifies the common container:

$(document).ready(function () {
    $(".toggle").click(function () {
        $(this).closest(".container").find(".text-hidden").slideToggle();
    });
});

Example:

$(document).ready(function () {
    $(".toggle").click(function () {
        $(this).closest(".container").find(".text-hidden").slideToggle();
    });
});
.text-hidden {
    display: none;
}
.toggle {
    cursor: pointer;
    color: blue;
}
<div >
    <div>Always visible (<a >toggle hidden</a>)</div>
    <div >Hidden by default</div>
</div>

<div >
    <div>Always visible (<a >toggle hidden</a>)</div>
    <div >Hidden by default</div>
</div>

<div >
    <div>Always visible (<a >toggle hidden</a>)</div>
    <div >Hidden by default</div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Related