1

I have situation Like I have a Wrapper div and a Child div and I am doing console.log('any text') when I am clicking the Wrapper div its is consoling the text {which makes sense to me} But When I am clicking the Child div it Still consoles the Text. {Which is weird

let test = document.querySelector('.test')
test.addEventListener('click', function() {
        console.log('wrapper clicked')
    })
.test{
  width:100%;
  heightL:100vh;
  display: flex;
  justify-content: center;
  align-items:center;
}
.exam{
   height: 100vh;
  width: 50%;
  color:white;
  font-family:sans-serif;
   display: grid;
   place-items:center;
  background: #000;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div class="test">
    <div class="exam">
      <h1>Click Me</h1>
    </div>
  </div>
</body>
</html>

to me}

So I want to know why this is happening Like when I am clicking the Child div why it Still consoles the text? and How to make it only console the text when the wrapper is clicked not the child?

Shayan Kanwal
  • 542
  • 4
  • 15

2 Answers2

0

In javascript when you add an event listener to a tag that has children, if you click on the children, the event will be fired because the children inherit the event listeners.

Marcos-MD
  • 86
  • 9
0

Because it is like your wrapper contains its children elements so it definitely works as you mentioned. So, my idea is you should put the text outside of the wrapper. Like this and some css trick.

 let test = document.querySelector('.exam')
    test.addEventListener('click', function() {
            console.log('wrapper clicked')
        })
.test{
          width:100%;
          height:100vh;
          display: flex;
          justify-content: center;
          align-items:center;
          background: red;
        }
        .exam{
           height: 100vh;
          width: 50%;
          color:white;
          font-family:sans-serif;
           display: grid;
           place-items:center;
          background: #000;
          position: relative;
        }

        .text {
        position: absolute;
        color:white;
        }
<!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      <div class="test">
        <div class="exam">
         &nbsp;
        </div>
         <h1 class="text">Click Me</h1>
      </div>
    </body>
    </html>