简体   繁体   中英

How to make the whole div clickable?

I have a div with contents in it:

<div class="block">
    <img src='...'>
    <span>...</span>
</div>

I set up a JavaScript Event Listener when someone clicks on the div :

document.body.addEventListener("click", function(e) {
    if (e.target.tagName === 'DIV' && e.target.classList.contains("block")){
        (code)
    }
}

It works when I click on the area of the div that has no content. But it doesn't works, when I click to the image or to the text.
How can I get this at the whole div working?

The event.target is the element you clicked on. If you do not directly click on the div then your code will not match your tests because you are clicking on a child element.

So when you are using event delegation and you want to know if an element or one of its children is clicked on, you need to walk up the tree to see if it is that element. You can do that with closest

 document.body.addEventListener("click", function(e) { if (e.target.closest('div.block')) { console.log('clicked', Date.now()); } });
 <h2>Example</h2> <div class="block"> <img src='http://placekitten.com/g/200/300'> <span>foo bar kitten</span> </div>

welcome to SO. You can add the event listener on the div itself and then perform whatever code you like. The reason it doesn't work in your case is because you are adding the event listener to the whole body and thus as the event handler is called, it doesn't recognize the elements you are clicking on even if they are inside the div .

Try this instead:

document.querySelector('div#block').addEventListener("click", function(e) {
  // code...
});

Try to give an id to div and add your event listener to that.

<div id="myDiv" class="content">
    // your content goes here
</div>

And in javascript

const myDiv = document.getElementById("myDiv");
myDiv.addEventListener("click", (event) => {
   // your function goes here
})

There are many ways you can do it. But In my opinion the best way is to make anything clickable in JS is use onClick() function. You can simply use onClick=functionName()

 function changeBackground(){ let block = document.getElementsByClassName('block'); block[0].style.backgroundColor = "green"; }
 .block{ height: 50px; border: 1px solid; }
 <div class="block" onClick="changeBackground()"> <div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM