Reputation: 1566
First of all Hello to everyone, and sorry for my English.
Of course i did not understand completely the use of return within event handlers.
and i would like receive if possible some clarification in this regard.
In this document i have som nested elements Fiddle.
Each element has an event handler that colors the same element of red in bubbling phase.
My question is: why with jQuery i can stop event propagation with return false and whit javascript i can't do the same thing?
Any suggestions will be read with pleasure, thank you all.
<!DOCTYPE HTML>
<html>
<head>
<style>
.x{border-radius:250px;position: absolute;background-color:#CCC;border:1px solid #666;top: 24px; left: 24px;}
#el1{height: 200px;width: 200px;}
#el2{height: 150px;width: 150px;}
#el3{height: 100px;width: 100px;}
#el4{height: 50px;width: 50px;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// first snippet i can't use return false
function init(){
var elements = document.getElementsByClassName('x')
for(var i=0; i<elements.length; i++) {
elements[i].addEventListener('click',function(e){
this.style.backgroundColor='red'
alert("clik")
/*return false*/
},false)
/* return false*/
}
}
document.addEventListener('DOMContentLoaded',init,false);
// second snippet i can use return false
/*$(document).ready(function(){
$('div.x').click(function(){
$(this).css({'background-color':'red'})
alert("clik")
return false
})
})*/
</script>
</head>
<body>
<div id="el1" class="x">
<div id="el2" class="x">
<div id="el3" class="x">
<div id="el4" class="x"></div>
</div>
</div>
</div>
</body>
</html>
Upvotes: 1
Views: 2222
Reputation: 11
<a href = "http://stackoverflow.com/" id = "a">http://stackoverflow.com/</a>
$("#a").click(function(){
return false;
});
document.getElementById("a").onclick = function(){
return false;
}
document.getElementById("a").addEventListener("click",function(e){
e.stopPropagation();
e.preventDefault();
//the same function to "return false" in the above two method.
},false);
Upvotes: 1