Skip to content Skip to sidebar Skip to footer

Click Event On Child Div Trigger Action Despite Click Handler Was Set On Parent Using AddEventListener (event Bubbling Was Disabled))

I have three div boxes The first div main has an id of 'main' and contains two other boxes with id 'menu_header' and 'menu_options' this is my html

Solution 1:

You can restrict event bubbling by 2 scenario. 1. Put Click event on each DOM object, means child to parent and put event.stropPropagation(). 2. Identify the DOM object using e.target.id and return "false".[We are using this]

Code below

<script>
        function test(e) {
            if (e.target.id == "menu_header") { return }
            else if (e.target.id == "menu_options") { return }
            $('#menu_header').animate({ top: '-10' }, 1000);
            var t = document.getElementById('menu_header')
            t.setAttribute('top','40px');
            t.style = "position:relative;border:solid black;background:red;width:100px;top:60px;height:100px;"
        }
         window.onload = function () {
        document.getElementById('main').addEventListener('click', test, false);
    }
</script>

Solution 2:

Try to stop propagation in the child element. See here.

function test(){
 $('#menu_header').animate({top:'10'},1000);
  //var t=document.getElementById('menu_header')
 // t.setAttribute('top','40px');
  //t.style="position:relative;border:solid black;background:red;width:100px;top:60px;height:100px;"
}

function stopPropagation(e){
    e.stopPropagation();
}

document.getElementById('main').addEventListener('click',test,false);

document.getElementById('menu_header').addEventListener('click',stopPropagation,false);

Post a Comment for "Click Event On Child Div Trigger Action Despite Click Handler Was Set On Parent Using AddEventListener (event Bubbling Was Disabled))"