I have two divs, a big one and a smaller over the other, each div has its own OnClick method. The problem I have is when I clicked the smaller div, the big div’s OnClick method is called too.
Who can I avoid that?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The best way to detect which element was clicked is to analyze target of event ( click event ). I have prepared small example for this case. You can see it in code below.
function amIclicked(e, element) { e = e || event; var target = e.target || e.srcElement; if(target.id==element.id) return true; else return false; } function oneClick(event, element) { if(amIclicked(event, element)) { alert('One is clicked'); } } function twoClick(event, element) { if(amIclicked(event, element)) { alert('Two is clicked'); } }This javascript method can be called before you execute your script
Example
<style> #one { width: 200px; height: 300px; background-color: red; } #two { width: 50px; height: 70px; background-color: yellow; margin-left: 10; margin-top: 20; } </style> <div id="one" onclick="oneClick(event, this);"> one <div id="two" onclick="twoClick(event, this);"> two </div> </div>I hope this helps.