DEV Community

Discussion on: Not toggling between divs

Collapse
expressgradient profile image
Praneeth

Hi, just remove the this in your addEventListener part and change it to btn. And also one suggestion, if you just wanna toggle the status, add the attribute called playStatus to the root div, which is like container to those three divs and simply add and remove your divs to that attribute, instead of changing the status on every div.

Collapse
rusty_xx profile image
Grey_W I N D Author

Thanks for the feedback. i have tried changing this to btn and still doesn't work. What I mean is that I have 3 div elements and those elements have a <button class='play'> each. And whenever a button is clicked it should indicate on the parent element which is the div that the button is playing a audio. And when i click on the second button from div number two, the data-status='isPlaying' should be on the second div and not the first one anymore

Collapse
expressgradient profile image
Praneeth

Alrighty, this is my markup,

<div class="root">
        <div id="one">
            <button class="play">Play</button>
        </div>
        <div id="two">
            <button class="play">Play</button>
        </div>
        <div id="three">
            <button class="play">Play</button>
        </div>
</div>

And this is my script

const root = document.querySelector(".root");
const buttons = document.querySelectorAll(".play");

[...root.children].forEach(child => {
    child.playStatus = false;
});

root.currentPlayDivId = "";

[...buttons].forEach(button => button.addEventListener("click", () => {
    button.parentNode.playStatus = true;

    if(root.currentPlayDivId !== "") {
        const previousPlayDiv = document.getElementById(root.currentPlayDivId);
        previousPlayDiv.playStatus = false;
    }

    root.currentPlayDivId = button.parentNode.id;

    console.log(root.currentPlayDivId);
    [...root.children].forEach(child => console.log(child.id, child.playStatus));
}));
Thread Thread
rusty_xx profile image
Grey_W I N D Author

Thank you so much...instead of using button.parentNode.playStatus i used it as a dataset so I can retrieve it later on...Thanks