DEV Community

Grey_W I N D
Grey_W I N D

Posted on

Not toggling between divs

I have 3 divs as parent elements of a button and what I want is toggle <div data-status='isPlaying'>...</div> between the 3 divs.
Below is the code for better understanding

// the button element
const play = document.querySelectorAll('.play');

Array.from(play).forEach((btn, i) => {
   btn.addEventListener('click', function () {
      this.parentNode.dataset.status = 'isPlaying'
   })

   btn.parentNode.dataset.status = 'notPlaying'
})
Enter fullscreen mode Exit fullscreen mode

Please what's wrong with this code and why isn't it working... Thanks

Top comments (4)

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

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

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