Problems with clicking on child elements of div

Asked

Viewed 54 times

0

I am developing a project where creates dynamically, several div with the class "musicItem" and for each div I have associated a data-musicId, and also I have a click on this div that when clicking I do some actions but for this I need to know the "data-musicid", the problem is that if I click on the div everything happens perfectly, but if you click on some child element of it gives error. It would be possible to solve this problem with javascript vanilla, without jquery?

Click detection code in the div:

const musicItens = document.querySelectorAll('.musicItem');
    for (const music of musicItens) {
        music.addEventListener('click', function(event) {
            const clickedmusic = event.target.attributes['data-musicid'].value;
            this.play(clickedmusic);
        }.bind(this));
    }

Sons of the Div:

        <div class="musicItem" data-musicid="1">
        <div class="musicPhoto">
            <img src="assets/images/3348986.jpg">
        </div>
        <div class="musicData">
            <p>Malha Suprema - Judas</p>
            <p>ACERT</p>
        </div>
        <div class="btnPlayer">
            <button class="playerBtn">
                <span class="playerImg">
                    <i class="far fa-play-circle"></i>
                </span>                 
            </button>
        </div>
    </div>
  • 1

    Guy from what I understand you want to click on an element with the class musicItem you want to know the data-musicid and give a .play() in it?

  • Yes call the play function()

1 answer

2


Hello,

It turns out that when you send an event in an element that contains child elements that also contains events, by clicking on a child element, the event click parent element is also fired.

To fix this, you can add a event.stopPropagation();

It would be something like:

music.addEventListener('click', function(event) {
    event.stopPropagation();
  • The problem is that I want to detect the click on everything including on the children elements and that is why I applied immediately on the father div, so the children also inherit the click and can return me the father’s date-musicid, but the children are returning me Uncaught Typeerror: Cannot read Property 'value' of Undefined

  • 1

    @Tomás then tested here and the problem is that the event click is being referenced in the element you are clicking, for example, when you click on the image, it tries to grab the attribute data-musicid image, and there is no attribute in it. To solve, you do the following: exchange const clickedmusic = event.target.attributes... for const clickedmusic = music.attributes["data-musicid"].value;

  • 1

    Thank you @Lucas Bittencourt was the problem!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.