Search code examples
javascripthtmljqueryclasselement

How to use Javascript on one specific div (multiple divs have the same class)


I have a Javascript file that opens a div when it is clicked.

let rotation1 = 0;
function rotateImg1() 
{
    rotation1 += 180; // add 90 degrees, you can change this as you want
    if (rotation1 === 360) 
    { 
        // 360 means rotate back to 0
        rotation1 = 0;
    }
    document.querySelector(".exampleboxheadercursoricon1").style.transform = `rotate(${rotation1}deg)`;
}
let transitionIsHappening1 = false;
$(".examplebutton1").click(function() 
{
    if (transitionIsHappening1) return;
    transitionIsHappening1 = true;
    setTimeout(() => transitionIsHappening1 = false, 500);
    $(".exampledropdown").slideToggle(500);
    rotateImg1();
});

I have multiple divs with the same class. (the classes are "examplebutton1" and "examplecontent1")

<div class="examplecontainer col-4">
    <div class="examplebox examplebutton1">
        <div class="exampleboxheader">
title
            <i class="fa fa-chevron-down pull-right exampleboxheadercursoricon1"  aria-hidden="true"></i>
        </div>
        <div class="exampledropdown examplecontent1">
            <div class= "exampledropdowntext1">
abc
            </div>
            <div class="container-fluid w-tapvideo">
                <iframe id="iframevideo" class="iframevideo" title="video" frameborder="0" allow="encrypted-media;" allowfullscreen src="https://www.youtube-nocookie.com/embed/hz_kk_0mG3A?autoplay=0&controls=1&showinfo=0&loop=1"></iframe>
            </div> 
            <a href="beginner/aiminglss.html" class="lsslink"> 
                <div>
                    Full Lesson 🡒
                </div>
            </a>
        </div>
    </div>
</div>

I'm trying to make only the box that was clicked on by the user, open.

I'm trying not to use a ton of ids because I have a lot of divs/boxes that need the same Javascript applied. Also, I tried using $(this).siblings(".examplecontent1"), but it didn't work (idk how to use it, im new).


Solution

  • You can directly select the elements by class with the clicked element as the context.

    Here is a simplified version of the code that works for any number of elements:

    $('.examplebutton1').click(function(e) {
        const dropdown = $('.exampledropdown', this);
        if (dropdown.is(':animated')) return;
        dropdown.slideToggle(500);
        const icon = $('.exampleboxheadercursoricon1', this);
        icon.css('rotate', ((parseFloat(icon.css('rotate')) || 0) + 180) % 360 + 'deg');
    });