Wednesday, May 15, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  112] [ 1]  / answers: 1 / hits: 27156  / 9 Years ago, wed, november 11, 2015, 12:00:00

I want to be able to click anywhere inside the body except that one specific element. I can't find out what's wrong with the code I have done.



When I click on the one specific element .except inside body, I don't want it to hide but when I click on body it should hide.



HTML



<html>
<head>
<title>Click anywhere except that specific element</title>
</head>
<body id=wrapper>
<center>
<div id=except></div>
</center>
</body>
</html>


JS



var body = document.getElementById('wrapper');
var except = document.getElementById('except');

if(body.addEventListener)
body.addEventListener(click, function(){bodyClick(yes)}, false);
else
body.attachEvent(onclick, bodyClick);

function bodyClick(clicked){

except.addEventListener(click, exceptClick,false);
function exceptClick(){
bodyClick(no);
if(clicked === yes)
except.style.display = none;
}

if(clicked === yes)
except.style.display = none;
else
except.style.display = show;

}


Any help is appreciated. Forgive me for the incorrect formatting (it's my first post here). Thank You!


More From » html

 Answers
63

You need to stopPropagation to the outer element.



Here's a simple illustration: http://jsfiddle.net/5mhqrhwk/3/



var body = document.getElementById('wrapper');
var except = document.getElementById('except');

body.addEventListener(click, function () {
alert(wrapper);
}, false);
except.addEventListener(click, function (ev) {
alert(except);
ev.stopPropagation(); //this is important! If removed, you'll get both alerts
}, false);


HTML:



<div id=wrapper>
<center>
<div id=except></div>
</center>
</div>

[#64432] Monday, November 9, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byronkodyo

Total Points: 552
Total Questions: 87
Total Answers: 104

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
;