Home > Back-end >  How to make the whole div clickable?
How to make the whole div clickable?

Time:08-25

I have a div with contents in it:

<div >
    <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?

CodePudding user response:

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 >
    <img src='http://placekitten.com/g/200/300'>
    <span>foo bar kitten</span>
</div>

CodePudding user response:

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...
});

CodePudding user response:

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

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

And in javascript

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

CodePudding user response:

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  onClick="changeBackground()">

<div>

  • Related