0

I have span inside a span with both onclick function. But when I click inner span it runs like the outer span is clicked

<article onclick="location='/Code1.php?'" >
    <!--Run Code1.php-->            
    <span onclick="location='/Code2.php'"  >
        <!--Run Code2.php-->
    </span>
    <!--Run Code1.php-->
</article>

It runs Code1.php whether I click on Code1.php or Code2.php. Article and span are overlapped, so click on span is also considered as click on article.

Code2.php should be executed when it is clicked on span, and Code1.php should be executed when clicked on article except the part of that span inside article.

  • 1
    you might want to investigate event bubbling - this might be of use https://javascript.info/bubbling-and-capturing or this https://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing – Professor Abronsius Sep 10 '19 at 07:27

1 Answers1

0

You could add a click event handler because you will need event.stopPropagation() also see the change in HTML where I changed the onclick to data-onclick ...

var elements = document.querySelectorAll('.xxx');
elements.forEach(function(element){
  element.addEventListener('click', function(event){
      event.stopPropagation(); // this is needed, otherwise if you click on Run Code2.php it will also run code1.php
      console.log('clicked one', this.getAttribute('data-onclick'));
      // now you can follow the link, just uncomment the next line
      // window.location.href =  this.getAttribute('data-onclick');
  });
});
.xxx {
  margin: 10px;
  padding: 10px;
  border: solid 4px green;
  background-color: orange;
  cursor: pointer;
}
<article class="xxx" data-onclick="/Code1.php?" >
    Run Code1.php           
    <span class="xxx"  data-onclick="/Code2.php"  >
        Run Code2.php
    </span>
    Run Code1.php
</article>

let me know, if needed, all the same can also be achieved without changing the HTML, but this is easyier I believe to understand the problem and the workaround

caramba
  • 21,963
  • 19
  • 86
  • 127
  • It did'nt worked, It even didnt went inside elements.forEach(function(element). I dont know much about jq + I dont now even I get the correct link in window.location.href, how will I open that file Code1.php – Usama Munir Sep 10 '19 at 12:23