0

Hi my HTML code is like

<div onclick="alert('layer 4');">
  <h1>layer 4</h1>
  <div onclick="alert('layer 3');" >
      <h1>layer 3</h1>
         <div onclick="alert('layer 2');">
            <h1>layer 2</h1>
             <div onclick="alert('layer 1');">
                <h1>layer 1</h1>
             </div>
        </div>
   </div>
 </div>

So when i click the layer 1 then all the click events for all 4 layers will get triggered because of event bubling. We can use stop propagation to stop the bubbling. All i want to know is that if i click the layer 1 is it possible to skip the click function of the 1st and 2nd layer then execute 3rd layer's click function and skip the 4th layer's function? How can i do that?

Deepthi S
  • 273
  • 1
  • 9
giri dharan
  • 157
  • 4
  • 12

2 Answers2

2

Here is the example code to achieve the required functionality, what I have done you can do that by providing ids or classes to corresponding elements also.

So according to the below code, only 'layer 3' alert will come, if you click on 'layer 1' or layer 2' or 'layer 3' -

function showAlert(){

if(event.currentTarget.firstElementChild.textContent=='layer 3')
 alert(event.currentTarget.firstElementChild.textContent);
}
<div onclick="showAlert()">
   <h1>layer 4</h1>
   <div onclick="showAlert()" >
      <h1>layer 3</h1>
      <div onclick="showAlert()">
         <h1>layer 2</h1>
         <div onclick="showAlert()">
            <h1>layer 1</h1>
         </div>
      </div>
   </div>
</div>
Ayush Sharma
  • 2,057
  • 15
  • 25
1

I think there are many different ways to accomplish this. Depending on what should happen when you click on a different layer then layer 1.

Either way I'm not to sure how to do it with inline javascript. You should try to avoid it as there are ways but that looks complicated. Read this for more information

It is much more simple to add a data attribute to the element and then add an eventListener on that element. That gives you lots of benefits.

Try this code:

var executeFunctionForLayer = 3;

var layers = document.querySelectorAll('[data-layer]');

layers.forEach(function(element, index){
    element.addEventListener("click", function(event){
        if(parseInt(element.dataset.layer, 10) === executeFunctionForLayer) {
            // here we do the crazy function stuff
            alert('layer ' + element.dataset.layer);
            
            // after this one stop from bubbeling
            event.stopPropagation();
        } 
        event.preventDefault();  // prevent from default 
        return;
    });
    
});
<div data-layer="4">
  <h1>layer 4</h1>
  <div data-layer="3">
      <h1>layer 3</h1>
      <div data-layer="2">
            <h1>layer 2</h1>
            <div data-layer="1">
                <h1>layer 1</h1>
             </div>
        </div>
   </div>
 </div>
caramba
  • 21,963
  • 19
  • 86
  • 127