White Maskers White Maskers - 17 days ago 6
CSS Question

How to give effect on click on outside of a div area?



document.getElementById("red").addEventListener("click",function(){
document.getElementById("red").style.backgroundColor = "yellow";
document.getElementById("red").style.color = "#000";


});

document.getElementById("green").addEventListener("click",function(){
document.getElementById("red").style.backgroundColor = "red";
document.getElementById("red").style.color = "#fff";
});

#red{
width:50px;
height:100px;
background-color:red;
color:#fff;
text-align:center;
margin-bottom:10px;
}

#green{
width:100px;
height:50px;
background-color:green;
color:#fff;
text-align:center;
}

<div id="red">div area1</div>
<div id="green"> div area2</div>





Is it possible to detect a click on outside of an div area and perform an action on that.In the above code I'm tried to change the colour of div#red on click on the div#green(background:red; color : white) or on an outside click((background:blue; color : white) and on an own click(background:yellow; color : black). consider there are several elements on this page ,then how to detect an click on outside of div#red and apply effects ?

Answer

You should use the event passed to the listener on the EventListener function. The event, contains a target property, which is the element that received the click. Check the target id and do what you need on each case. Here is a sample:

document.getElementsByTagName("html")[0].addEventListener("click",function(e){
	if(e.target.id == "red"){
		document.getElementById("red").style.backgroundColor = "yellow";
		document.getElementById("red").style.color = "#000";
	}
	else{
		document.getElementById("red").style.backgroundColor = "red";
		document.getElementById("red").style.color = "#fff";
	}
});
#red{
  width:50px;
  height:100px;
  background-color:red;
  color:#fff;
  text-align:center;
  margin-bottom:10px;
  }

#green{
  width:100px;
  height:50px;
  background-color:green;
  color:#fff;
  text-align:center;
  }
<div id="red">div area1</div>
<div id="green"> div area2</div>