简体   繁体   中英

Javascript prevent event propagation through element

Working with google maps which has infowindows that popup. These infowindows have images which are click-able. As a result I need to be able to propagate events in the infowindow. However I am also able to click THROUGH the infowindow to other markers which causes the current infowindow to close and it to open a new infowindow.

I dont think this issue is specific to google maps. Is there a way to stop events from propagating through an element?

Thought the below code would help but it didnt.

$(document).on('touchstart', '.infoWindow', function(e){
  if ($(e.currentTarget) == $(this)) e.stopPropagation();
 });
 if ($(e.currentTarget) == $(this)) 

This is never true. It creates two distinct jQuery instances, which - even if they contain the same element - are not the same object. You might have wanted to do

 if (e.currentTarget == this) 

but this is always true - by definition of the event dispatch algorithm, the this value of an event listener and the currentTarget of the event object always refer to the same thing. Hell, even jQuery does this .

So you should just write

$(document).on('touchstart', '.infoWindow', function(e){
    e.stopPropagation();
});

to prevent touchstart events from bubbling through your infoWindows.

You cannot stop the event propagation when you use event delegation. Event delegation relies on the bubbleing event, so by the time the delegated handler gets the event, the event already bubbled through every other element. You need to attach your event listener directly to the element.

$('.infoWindow').on('touchstart', function(e){
    e.stopPropagation();
});

Event delegation works by adding the event listener to the document , then every time the document receives that touchstart event, jQuery checks the source element and all of its parent if they match the given selector. If one matches, the handler gets invoked. This is why you don't need to add the listener every time you add a new element that would match the given selector.

Setting a background color of the .infoWindow element might be a solution. If it should be transparent, you can use as follows:

background-color: rgba(255, 0, 0, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM