Reputation: 43
I'm trying to stop the propagation on an event of all the anchors in a div that has a click event attached but only the .click
jquery function fire e.stopPropagation();
, the .on('click', 'a', function());
don't.
Code example that works, the click on the anchor do not fire the click on the div when clicked
<div class="clickedDiv" data-url="http://myurl.com">
<a class="clickedA">my link</a>
</div>
<script>
$('.clickedA').click(function(e) {e.stopPropagation();});
$('.clickedDiv').click(function(e) {
var url = $(this).data('url');
window.location.href = url;
});
</script>
Code exampe that doesn't work, the click on the anchor fire both click, the anchor itself and the div
<div class="clickedDiv" data-url="http://myurl.com">
<a class="clickedA">my link</a>
</div>
<script>
$('.clickedDiv').on('click', 'a', function(e) {e.stopPropagation();});
$('.clickedDiv').click(function(e) {
var url = $(this).data('url');
window.location.href = url;
});
</script>
Upvotes: 3
Views: 80
Reputation: 81
First, you are missing
)
at the end of 2 scripts this could cause the problem.
Second, If this is just typo, the both code should have the same results, the event fires when click on the div only and didn't fire when click on the anchor.
check this fiddle here https://jsfiddle.net/3tg96ru1/2/
Third, a better way to do that is to do it in the same function and check if the clicked element is not the anchor then execute the function like this:
$('.clickedDiv3').click(function(e) {
var target = e.target;
if (!$(target).is('.clickedA3')) {
alert('fffff');
} });
for more details about difference between .on('click') vs .click() check this link: Difference between .on('click') vs .click()
Upvotes: 1
Reputation: 67505
You should prevent the default action instead using e.preventDefault()
, should be :
$('.clickedDiv').click(function(e) {
e.preventDefault();
var url = $(this).data('url');
window.location.href = url;
}
NOTE : No need for the other click event :
$('.clickedDiv').on('click', 'a', function(e) {e.stopPropagation();});
Hope this helps.
Upvotes: 4