Reputation:
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 ?
Upvotes: 0
Views: 67
Reputation: 26
What you can do is add a click even on the document itself and use the event object passed to the click function to help detect which item is being clicked on. With that information you can detect if the click came from inside or outside the element
document.addEventListener("click",function(ev){
if(ev.target.id !== "red" && ev.target.id !== "green"){
document.getElementById("red").style.backgroundColor = "blue";
}
})
Here's a working fiddle
Upvotes: 0
Reputation: 1257
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>
Upvotes: 1