Safari Web Content Guide

  • Table of Contents
  • Jump To…
  • Download Sample Code

Handling Events

This chapter describes the events that occur when the user interacts with a webpage on iOS. Forms and documents generate the typical events in iOS that you might expect on the desktop. Gestures handled by Safari on iOS emulate mouse events. In addition, you can register for iOS-specific multi-touch and gesture events directly. Orientation events are another example of an iOS-specific event. Also, be aware that there are some unsupported events such as cut, copy, and paste.

Gestures that the user makes—for example, a double tap to zoom and a flick to pan—emulate mouse events. However, the flow of events generated by one-finger and two-finger gestures are conditional depending on whether or not the selected element is clickable or scrollable as described in One-Finger Events and Two-Finger Events .

In addition, you can turn off the default Safari on iOS behavior as described in Preventing Default Behavior and handle your own multi-touch and gesture events directly. Handling multi-touch and gesture events directly gives developers the ability to implement unique touch-screen interfaces similar to native applications. Read Handling Multi-Touch Events and Handling Gesture Events to learn more about DOM touch events.

If you want to change the layout of your webpage depending on the orientation of iOS, read Handling Orientation Events .

See Supported Events for a complete list of events supported in iOS.

On iOS, emulated mouse events are sent so quickly that the down or active pseudo state of buttons may never occur. Read Highlighting Elements for how to customize a button to behave similar to the desktop.

It’s very common to combine DOM touch events with CSS visual effects. Read Safari CSS Visual Effects Guide to learn more about CSS visual effects.

One-Finger Events

This section uses flow charts to break down gestures into the individual actions that might generate events. Some of the events generated on iOS are conditional—the events generated depend on what the user is tapping or touching and whether they are using one or two fingers. Some gestures don’t generate any events on iOS.

One-finger panning doesn’t generate any events until the user stops panning—an onscroll event is generated when the page stops moving and redraws—as shown in Figure 6-1 .

The panning gesture

Displaying the information bubble doesn’t generate any events as shown in Figure 6-2 . However, if the user touches and holds an image, the image save sheet appears instead of an information bubble.

The touch and hold gesture

Finally, a double tap doesn’t generate any events either as shown in Figure 6-3 .

The double-tap gesture

Mouse events are delivered in the same order you'd expect in other web browsers illustrated in Figure 6-4 . If the user taps a nonclickable element, no events are generated. If the user taps a clickable element, events arrive in this order: mouseover , mousemove , mousedown , mouseup , and click . The mouseout event occurs only if the user taps on another clickable item. Also, if the contents of the page changes on the mousemove event, no subsequent events in the sequence are sent. This behavior allows the user to tap in the new content.

One-finger gesture emulating a mouse

Two-Finger Events

The pinch open gesture does not generate any mouse events as shown in Figure 6-5 .

The pinch open gesture

Figure 6-6 illustrates the mouse events generated by using two fingers to pan a scrollable element. The flow of events is as follows:

If the user holds two fingers down on a scrollable element and moves the fingers, mousewheel events are generated.

If the element is not scrollable, Safari on iOS pans the webpage. No events are generated while panning.

An onscroll event is generated when the user stops panning.

Two-finger panning gesture

Form and Document Events

Typical events generated by forms and documents include blur , focus , load , unload , reset , submit , change and abort . See Supported Events for a complete list of supported events on iOS.

Handling Multi-Touch Events

You can use JavaScript DOM touch event classes available on iOS to handle multi-touch and gesture events in a way similar to the way they are handled in native iOS applications.

If you register for multi-touch events, the system continually sends TouchEvent objects to those DOM elements as fingers touch and move across a surface. These are sent in addition to the emulated mouse events unless you prevent this default behavior as described in Preventing Default Behavior . A touch event provides a snapshot of all touches during a multi-touch sequence, most importantly the touches that are new or have changed for a particular target. The different types of multi-touch events are described in Touch Class Reference .

A multi-touch sequence begins when a finger first touches the surface. Other fingers may subsequently touch the surface, and all fingers may move across the surface. The sequence ends when the last of these fingers is lifted from the surface. An application receives touch event objects during each phase of any touch.

Touch events are similar to mouse events except that you can have simultaneous touches on the screen at different locations. A touch event object is used to encapsulate all the touches that are currently on the screen. Each finger is represented by a touch object. The typical properties that you find in a mouse event are in the touch object, not the touch event object.

Note that a sequence of touch events is delivered to the element that received the original touchstart event regardless of the current location of the touches.

Follow these steps to use multi-touch events in your web application.

Register handlers for multi-touch events in HTML as follows:

Alternatively, register handlers in JavaScript as follows:

Respond to multi-touch events by implementing handlers in JavaScript.

For example, implement the touchStart method as follows:

Optionally, get all touches on a page using the touches property as follows:

Note that you can get all other touches for an event even when the event is triggered by a single touch.

Optionally, get all touches for the target element using the targetTouches property:

Optionally, get all changed touches for this event using the changedTouches property:

Access the Touch object properties—such as the target, identifier, and location in page, client, or screen coordinates—similar to mouse event properties.

For example, get the number of touches:

Get a specific touch object at index i :

Finally, get the location in page coordinates for a single-finger event:

You can also combine multi-touch events with CSS visual effects to enable dragging or some other user action. To enable dragging, implement the touchmove event handler to translate the target:

Typically, you implement multi-touch event handlers to track one or two touches. But you can also use multi-touch event handlers to identify custom gestures. That is, custom gestures that are not already identified for you by gesture events described in Handling Gesture Events . For example, you can identify a two-finger tap gesture as follows:

Begin gesture if you receive a touchstart event containing two target touches.

End gesture if you receive a touchend event with no preceding touchmove events.

Similarly, you can identify a swipe gesture as follows:

Begin gesture if you receive a touchstart event containing one target touch.

Abort gesture if, at any time, you receive an event with >1 touches.

Continue gesture if you receive a touchmove event mostly in the x-direction.

Abort gesture if you receive a touchmove event mostly the y-direction.

End gesture if you receive a touchend event.

Handling Gesture Events

Multi-touch events can be combined together to form high-level gesture events.

GestureEvent objects are also sent during a multi-touch sequence. Gesture events contain scaling and rotation information allowing gestures to be combined, if supported by the platform. If not supported, one gesture ends before another starts. Listen for GestureEvent objects if you want to respond to gestures only, not process the low-level TouchEvent objects. The different types of gesture events are described in GestureEvent in WebKit JS Framework Reference .

Follow these steps to use gesture events in your web application.

Register handlers for gesture events in HTML:

Alternatively, register handlers in JavaScript:

Respond to gesture events by implementing handlers in JavaScript.

For example, implement the gestureChange method as follows:

Get the amount of rotation since the gesture started:

The angle is in degrees, where clockwise is positive and counterclockwise is negative.

Get the amount scaled since the gesture started:

The scale is smaller if less than 1.0 and larger if greater than 1.0 .

You can combine gesture events with CSS visual effects to enable scaling, rotating, or some other custom user action. For example, implement the gesturechange event handler to scale and rotate the target as follows:

Preventing Default Behavior

The default behavior of Safari on iOS can interfere with your application’s custom multi-touch and gesture input. You can disable the default browser behavior by sending the preventDefault message to the event object.

For example, to prevent scrolling on an element in iOS 2.0, implement the touchmove and touchstart event handlers as follows :

To disable pinch open and pinch close gestures in iOS 2.0, implement the gesturestart and gesturechange event handlers as follows:

Handling Orientation Events

An event is sent when the user changes the orientation of iOS. By handling this event in your web content, you can determine the current orientation of the device and make layout changes accordingly. For example, display a simple textual list in portrait orientation and add a column of icons in landscape orientation.

Similar to a resize event, a handler can be added to the <body> element in HTML as follows:

where updateOrientation is a handler that you implement in JavaScript.

In addition, the window object has an orientation property set to either 0 , -90 , 90 , or 180 . For example, if the user starts with the iPhone in portrait orientation and then changes to landscape orientation by turning the iPhone to the right, the window’s orientation property is set to -90 . If the user instead changes to landscape by turning the iPhone to the left, the window’s orientation property is set to 90 .

Listing 6-1 adds an orientation handler to the body element and implements the updateOrientation JavaScript method to display the current orientation on the screen. Specifically, when an orientationchange event occurs, the updateOrientation method is invoked, which changes the string displayed by the division element in the body.

Listing 6-1   Displaying the orientation

Supported Events

Be aware of all the events that iOS supports and under what conditions they are generated. Table 6-1 specifies which events are generated by Safari on iOS and which are generated conditionally depending on the type of element selected. This table also lists unsupported events.

Copyright © 2016 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2016-12-12

Sending feedback…

We’re sorry, an error has occurred..

Please try submitting your feedback later.

Thank you for providing feedback!

Your input helps improve our developer documentation.

How helpful is this document?

How can we improve this document.

* Required information

To submit a product bug or enhancement request, please visit the Bug Reporter page.

Please read Apple's Unsolicited Idea Submission Policy before you send us your feedback.

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

addEventListener() does not work well on Safari #13929

@mlbonniec

mlbonniec Jun 9, 2020

Beta Was this translation helpful? Give feedback.

Replies: 1 comment

{{editor}}'s edit, mahish aug 5, 2021.

@mlbonniec

This discussion was converted from issue #13929 on June 09, 2020 09:11.

  • Numbered list
  • Unordered list
  • Attach files

Select a reply

Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

nlanka

addEventListener is not working in safari iPhone

Hi we are having an issue with iPhone on safari which is known issue. We we click on a button with addEventListener it is not opening the modal as expected. Here is the sample code we used.

if (document.readyState === 'complete') {

      this.initExternalTriggers;

    } else {

      if (window.addEventListener) {

        window.addEventListener('load', this.initExternalTriggers);

      } else {

        document.addEventListener && document.addEventListener("DOMContentLoaded", this.initExternalTriggers)

Posted on Nov 29, 2022 11:22 AM

Similar questions

  • Can't click buttons in Safari I suddenly can't click any buttons in safari. I try to fill out online forms and can't click the button to submit. 960 1
  • Safari suggestions doesn’t work My iPhone 13 running iOS 15 doesn’t come up with suggestions when you start typing in safari. This happens about 95% of the time. Very rarely it will work so I am doubtful it is anything to do with the settings. I have asked at the Genius Bar at my local Apple store and they didn’t have a clue either. Has anyone encountered this problem before or know of any fixes? 1129 1
  • Safari regularly loads blank pages but the page can be seen when in reader view. Why does this happen? When browsing in safari, it often loads blank pages (iPhone 8 plus and iPad Pro 11”) but the page can be seen when using reader view. Why does this happen? On the iPad Pro safari also loads some web pages so that only the left part of the page can be seen. This is also fixed through reader view. Is there any way to fix this without having to constantly use reader view? 2635 3

Loading page content

Page content loaded

There are no replies.

Using AbortController as an Alternative for Removing Event Listeners

Avatar of Carter Li

The idea of an “abortable” fetch came to life in 2017 when AbortController was released. That gives us a way to bail on an API request initiated by fetch() — even multiple calls — whenever we want.

Here’s a super simple example using AbortController to cancel a fetch() request:

You can really see its value when used for a modern interface of setTimeout . This way, making a fetch timeout after, say 10 seconds, is pretty straightforward:

But the big news is that addEventListener now accepts an Abort Signal as of Chrome 88 . What’s cool about that? It can be used as an alternate of removeEventListener :

What’s even cooler than that? Well, because AbortController is capable of aborting multiple cancelable requests at once, it streamlines the process of removing multiple listeners in one fell swoop. I’ve already found it particularly useful for drag and drop.

Here’s how I would have written a drag and drop script without AbortController , relying two removeEventListener instances to wipe out two different events:

With the latest update, addEventListener accepts the signal property as its second argument, allowing us to call abort() once to stop all event listeners when they’re no longer needed:

Again, Chrome 88 is currently the only place where addEventListener officially accepts an AbortSignal. While other major browsers, including Firefox and Safari, support AbortController , integrating its signal with addEventListener is a no go at the moment… and there are no signals (pun sorta intended) that they plan to work on it. That said, a polyfill is available .

Hey, this is really cool!, thanks for the post!

In the last JS example, shouldn’t abortController.signal be controller.signal ?, because there isn’t any variable called abortController

Fixed. Thanks.

Yeah, It doesn’t work.

If you look at the platform bug tickets listed in https://github.com/whatwg/dom/pull/919 , it actually looks like Firefox and Safari have both already implemented this.

Will the event handler function get garbage collected after we call controller.abort() ?

If not, it seems that using AbortController hurts performance.

It seems the feature is behind a flag in Chrome 88 and will only be enabled by default in Chrome 90 . As per signals from other browsers, this issue suggests the feature is planned for the Firefox 86 release.

…and the corresponding Webkit issue has been resolved, so I’m confident we’ll have good support soon!

While other major browsers, including Firefox and Safari, support AbortController, integrating its signal with addEventListener is a no go at the moment… and there are no signals (pun sorta intended) that they plan to work on it.

chromestatus.com is not a great place to track other vendors’ statuses, as they don’t track them automatically and they don’t update that part often…

Signals in event listeners are now supported on Firefox, but iOS and desktop Safari both still lack support.

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#browser_compatibility

We checked today if this is now working in all Browsers and I can confirm that Safari 15 and Firefox 101 also support this. If you have to support Safari 14 you can use this tiny Polyfill. https://github.com/nuxodin/lazyfill/blob/main/monkeyPatches/addEventListenerSignal.js

  • Skip to main content
  • Select language
  • Skip to search
  • Sign in Github

Usage notes

Other notes, specifications, browser compatibility.

The EventTarget method addEventListener() sets up a function that will be called whenever the specified event is delivered to the target. Common targets are Element , Document , and Window , but the target may be any object that supports events (such as XMLHttpRequest ).

addEventListener() works by adding a function or an object that implements EventListener to the list of event listeners for the specified event type on the EventTarget on which it's called.

  • capture : A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.
  • once : A Boolean indicating that the listener should be invoked at most once after being added. If true , the listener would be automatically removed when invoked.
  • passive : A Boolean which, if true , indicates that the function specified by listener will never call preventDefault() . If a passive listener does call preventDefault() , the user agent will do nothing other than generate a console warning. See Improving scrolling performance with passive listeners to learn more.
  • mozSystemGroup : A Boolean indicating that the listener should be added to the system group. Available only in code running in XBL or in the chrome of the Firefox browser.

Return value

The event listener callback.

The event listener can be specified as either a callback function or an object that implements EventListener , whose handleEvent() method serves as the callback function.

The callback function itself has the same parameters and return value as the handleEvent() method; that is, the callback accepts a single parameter: an object based on Event describing the event which has occurred, and it returns nothing.

For example, an event handler callback that can be used to handle both fullscreenchange and fullscreenerror might look like this:

Safely detecting option support

In older versions of the DOM specification, the third parameter of addEventListener() was a Boolean value indicating whether or not to use capture. Over time, it became clear that more options were needed. Rather than adding more parameters to the function (complicating things enormously when dealing with optional values), the third parameter was changed to an object which can contain various properties defining the values of options to configure the process of removing the event listener.

Because older browsers (as well as some not-too-old browsers) still assume the third parameter is a Boolean, you need to build your code to handle this scenario intelligently. You can do this by using feature detection for each of the options you're interested in.

For example, if you want to check for the passive option:

This creates an options object with a getter function for the passive property; the getter sets a flag, passiveSupported , to true if it gets called. That means that if the browser checks the value of the passive property on the options object, passiveSupported will be set to true ; otherwise, it will remain false . We then call addEventListener() to set up a fake event handler, specifying those options, so that the options will be checked if the browser recognizes an object as the third parameter. Then, we call removeEventListener() to clean up after ourselves. (Note that handleEvent() is ignored on event listeners that aren't called.)

You can check whether any option is supported this way. Just add a getter for that option using code similar to what is shown above.

Then, when you want to create an actual event listener that uses the options in question, you can do something like this:

Here we're adding a listener for the mouseup event on the element someElement . For the third parameter, if passiveSupported is true , we're specifying an options object with passive set to true ; otherwise, we know that we need to pass a Boolean, and we pass false as the value of the useCapture parameter.

If you'd prefer, you can use a third-party library like Modernizr or Detect It to do this test for you.

You can learn more from the article about EventListenerOptions from the Web Incubator Community Group .

Add a simple listener

This example demonstrates how to use addEventListener() to watch for mouse clicks on an element.

In this code, modifyText() is a listener for click events registered using addEventListener() . A click anywhere in the table bubbles up to the handler and runs modifyText() .

Event listener with anonymous function

Here, we'll take a look at how to use an anonymous function to pass parameters into the event listener.

Notice that the listener is an anonymous function that encapsulates code that is then, in turn, able to send parameters to the modifyText() function, which is responsible for actually responding to the event.

Event listener with an arrow function

This example demonstrates a simple event listener implemented using arrow function notation.

Please note that while anonymous and arrow functions are similar, they have different this bindings. While anonymous (and all traditional JavaScript functions) create their own this bindings, arrow functions inherit the this binding of the containing function.

That means that the variables and constants available to the containing function are also available to the event handler when using an arrow function.

Example of options usage

Click the outer, middle, inner containers respectively to see how the options work.

Before using a particular value in the options object, it's a good idea to ensure that the user's browser supports it, since these are an addition that not all browsers have supported historically. See Safely detecting option support for details.

Why use addEventListener ?

addEventListener() is the way to register an event listener as specified in W3C DOM. The benefits are as follows:

  • It allows adding more than a single handler for an event. This is particularly useful for AJAX libraries, JavaScript modules, or any other kind of code that needs to work well with other libraries/extensions.
  • It gives you finer-grained control of the phase when the listener is activated (capturing vs. bubbling).
  • It works on any DOM element, not just HTML elements.

The alternative, older way to register event listeners , is described below.

Adding a listener during event dispatch

If an EventListener is added to an EventTarget while it is processing an event, that event does not trigger the listener. However, that same listener may be triggered during a later stage of event flow, such as the bubbling phase.

Multiple identical event listeners

If multiple identical EventListener s are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener() method. Note however that when using an anonymous function as the handler, such listeners will NOT be identical since anonymous functions are not identical even if defined using the SAME unchanging source-code simply called repeatedly, even if in a loop. However, repeatedly defining the same named function in such cases can be more problematic. (see Memory issues below.)

The value of this within the handler

It is often desirable to reference the element on which the event handler was fired, such as when using a generic handler for a set of similar elements.

If attaching a handler function to an element using addEventListener() , the value of this inside the handler is a reference to the element. It is the same as the value of the currentTarget property of the event argument that is passed to the handler.

As a reminder, arrow functions do not have their own this context .

If an event handler (for example, onclick ) is specified on an element in the HTML source, the JavaScript code in the attribute value is effectively wrapped in a handler function which binds the value of this in a manner consistent with the addEventListener() ; an occurrence of this within the code represents a reference to the element.

Note that the value of this inside a function, called by the code in the attribute value, behaves as per standard rules . This is shown in the following example:

The value of this within logID() is a reference to the global object Window (or undefined in the case of strict mode ).

Specifying this using bind()

The Function.prototype.bind() method lets you specify the value that should be used as this for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. Note, however, that you'll need to keep a reference to the listener around so you can remove it later.

This is an example with and without bind() :

Another solution is using a special function called handleEvent() to catch any events:

Another way of handling the reference to this is to pass to the EventListener a function that calls the method of the object which contains the fields that need to be accessed:

Getting Data Into and Out of an Event Listener

It may seem that event listeners are like islands, and that it is extremely difficult to pass them any data, much less to get any data back from them after they execute. Event listeners only take one argument, the Event Object , which is automatically passed to the listener, and the return value is ignored. So how can we get data in and back out of them again? There are a number of good methods for doing this.

Getting Data into an Event Listener Using this

As mentioned above , you can use Function.prototype.bind() to pass a value to an event listener via the this reference variable.

This method is suitable when you don't need to know which HTML element the event listener fired on programmatically from within the event listener. The primary benefit to doing this is that the event listener receives the data in much the same way that it would if you were to actually pass it the data through its argument list.

Getting Data Into an Event Listener Using the Outer Scope Property

When an outer scope contains a variable declaration (with var ), all the inner functions declared in that scope have access to that variable (look here for information on outer/inner functions, and here for information on variable scope). Therefore, one of the simplest ways to access data from outside of an event listener is to make it accessible to the scope in which the event listener is declared.

Note: Although inner scopes have access to var variables from outer scopes, you cannot expect any changes to these variables to be accessible after the event listener definition, within the same outer scope. Why? Simply because by the time the event listener would execute, the scope in which it was defined would have already finished executing.

Getting Data Into and Out of an Event Listener Using Objects

Unlike most* functions in JavaScript, objects are retained in memory as long as a variable referencing them exists in memory. This, and the fact that objects can have properties, and that they can be passed around by reference, makes them likely candidates for sharing data among scopes. Let's explore this.

Note: Functions in JavaScript are actually objects. (Hence they too can have properties, and will be retained in memory even after they finish executing if assigned to a variable that persists in memory.)

Because object properties can be used to store data in memory as long as a variable referencing the object exists in memory, you can actually use them to get data into an event listener, and any changes to the data back out after an event handler executes. Consider this example.

In this example, even though the scope in which both the event listener and the interval function are defined would have finished executing before the original value of someObject.aProperty would have changed, because someObject persists in memory (by reference ) in both the event listener and interval function, both have access to the same data (i.e., when one changes the data, the other can respond to the change).

Note: Objects are stored in variabes by reference, meaning only the memory location of the actual data is stored in the variable. Among other things, this means variables that "store" objects can actually affect other variables that get assigned ("store") the same object reference. When two variables reference the same object (e.g., var a = b = {aProperty: 'Yeah'}; ), changing the data in either variable will affect the other.

Note: Because objects are stored in variables by reference, you can return an object from a function to keep it alive (preserve it in memory so you don't lose the data) after that function stops executing.

Legacy Internet Explorer and attachEvent

In Internet Explorer versions before IE 9, you have to use attachEvent() , rather than the standard addEventListener() . For IE, we modify the preceding example to:

There is a drawback to attachEvent() : The value of this will be a reference to the window object, instead of the element on which it was fired.

The attachEvent() method could be paired with the onresize event to detect when certain elements in a webpage were resized. The proprietary mselementresize event, when paired with the addEventListener method of registering event handlers, provides similar functionality as onresize , firing when certain HTML elements are resized.

Compatibility

You can work around addEventListener() , removeEventListener() , Event.preventDefault() , and Event.stopPropagation() not being supported by Internet Explorer 8 by using the following code at the beginning of your script. The code supports the use of handleEvent() and also the DOMContentLoaded event.

Note: useCapture is not supported, as IE 8 does not have any alternative method. The following code only adds IE 8 support. This IE 8 polyfill only works in standards mode: a doctype declaration is required.

Older way to register event listeners

addEventListener() was introduced with the DOM 2 Events specification. Before then, event listeners were registered as follows:

This method replaces the existing click event listener(s) on the element if there are any. Other events and associated event handlers such as blur ( onblur ) and keypress ( onkeypress ) behave similarly.

Because it was essentially part of DOM 0 , this technique for adding event listeners is very widely supported and requires no special cross–browser code. It is normally used to register event listeners dynamically unless the extra features of addEventListener() are needed.

Memory issues

In the first case above, a new (anonymous) handler function is created with each iteration of the loop. In the second case, the same previously declared function is used as an event handler, which results in smaller memory consumption because there is only one handler function created. Moreover, in the first case, it is not possible to call removeEventListener() because no reference to the anonymous function is kept (or here, not kept to any of the multiple anonymous functions the loop might create.) In the second case, it's possible to do myElement.removeEventListener("click", processEvent, false) because processEvent is the function reference.

Actually, regarding memory consumption, the lack of keeping a function reference is not the real issue; rather it is the lack of keeping a STATIC function reference. In both problem-cases below, a function reference is kept, but since it is redefined on each iteration, it is not static. In the third case, the reference to the anonymous function is being reassigned with each iteration. In the fourth case, the entire function definition is unchanging, but it is still being repeatedly defined as if new (unless it was [[promoted]] by the complier) and so is not static. Therefore, though appearing to be simply [[Multiple identical event listeners]], in both cases each iteration will instead create a new listener with its own unique reference to the handler function. However, since the function definition itself does not change, the SAME function may still be called for every duplicate listener (especially if the code gets optimized.)

Also in both cases, because the function reference was kept but repeatedly redefined with each add, the remove-statement from above can still remove a listener, but now only the last one added.

Improving scrolling performance with passive listeners

According to the specification, the default value for the passive option is always false. However, this introduces the potential for event listeners handling certain touch events (among others) to block the browser's main thread while it is attempting to handle scrolling, resulting in possibly enormous reduction in performance during scroll handling.

To prevent this problem, some browsers (specifically, Chrome and Firefox) have changed the default value of the passive option to true for the touchstart and touchmove events on the document-level nodes Window , Document , and or node of the current document, or null if no such element exists."> Document.body . This prevents the event listener from being called, so it can't block page rendering while the user is scrolling.

Note: See the compatibility table below if you need to know which browsers (and/or which versions of those browsers) implement this altered behavior.

You can override this behavior by explicitly setting the value of passive to false , as shown here:

On older browsers that don't support the options parameter to addEventListener() , attempting to use it prevents the use of the useCapture argument without proper use of feature detection .

You don't need to worry about the value of passive for the basic scroll event. Since it can't be canceled, event listeners can't block page rendering anyway.

  • EventTarget.removeEventListener()
  • Creating and triggering custom events
  • More details on the use of this in event handlers

Document Tags and Contributors

  • AccessOuterData
  • addEventListener
  • attachEvent
  • Detecting Events
  • Event Handlers
  • Event Listener
  • EventTarget
  • mselementresize
  • PassingData
  • Receiving Events
  • EventTarget()
  • addEventListener()
  • dispatchEvent()
  • removeEventListener()
  • CompositionEvent
  • EventListener
  • KeyboardEvent
  • MouseScrollEvent
  • MouseWheelEvent
  • MutationEvent
  • ProgressEvent

Learn the best of web development

Get the latest and greatest from MDN delivered straight to your inbox.

Thanks! Please check your inbox to confirm your subscription.

If you haven’t previously confirmed a subscription to a Mozilla-related newsletter you may have to do so. Please check your inbox or your spam filter for an email from us.

  • Skip to main content
  • Select language
  • Skip to search

EventTarget.addEventListener()

Safely detecting option support, improving scrolling performance with passive listeners.

The EventTarget.addEventListener() method adds the specified EventListener -compatible object to the list of event listeners for the specified event type on the EventTarget on which it is called. The event target may be an Element in a document, the Document itself, a Window , or any other object that supports events (such as XMLHttpRequest ).

  • capture : A  Boolean indicating that events of this type will be dispatched to the registered listener  before being dispatched to any EventTarget beneath it in the DOM tree.  
  • once : A Boolean indicating that the listener should be invoked at most once after being added. If true , the listener would be automatically removed when invoked.
  • passive : A Boolean indicating that the listener will never call preventDefault() . If it does, the user agent should ignore it and generate a console warning. See Improving scrolling performance with passive listeners to learn more.
  • mozSystemGroup : A Boolean indicating that the listener should be added to the system group. Available only in code running in XBL or in Firefox's chrome.

Before using a particular value in the options object, it's a good idea to ensure that the user's browser supports it, since these are an addition that not all browsers have supported historically. See Safely detecting option support for details.

In older versions of the DOM specification, the third parameter of addEventListener() was a Boolean value indicating whether or not to use capture. Over time, it became clear that more options were needed. Rather than adding more parameters to the function (complicating things enormously when dealing with optional values), the third parameter was changed to an object which can contain various properties defining the values of options to configure the process of removing the event listener.

Because older browsers (as well as some not-too-old browsers) still assume the third parameter is a Boolean, you need to build your code to handle this scenario intelligently. You can do this by using feature detection for each of the options you're interested in.

For example, if you want to check for the passive option:

This creates an options object with a getter function for the passive property; the getter sets a flag, passiveSupported , to true if it gets called. That means that if the browser checks the value of the passive property on the options object, passiveSupported will be set to true ; otherwise, it will remain false . We then call addEventListener() to set up a fake event handler, specifying those options, so that the options will be checked if the browser recognizes an object as the third parameter.

You can check whether any option is supported this way. Just add a getter for that option using code similar to what is shown above.

Then, when you want to create an actual event listener that uses the options in question, you can do something like this:

Here, we're adding a listener for the mouseup event on the element someElement . For the third parameter, if passiveSupported is true , we're specifying an options object with passive set to true ; otherwise, we know that we need to pass a Boolean, and we pass false as the value of the useCapture parameter.

If you'd prefer, you can use a third-party library like Modernizr or Detect It to do this test for you.

You can learn more from the article about EventListenerOptions from the Web Incubator Community Group .

Add a simple listener

In the above example, modifyText() is a listener for click events registered using addEventListener() . A click anywhere in the table bubbles up to the handler and runs  modifyText() .

If you want to pass parameters to the listener function, you may use an anonymous function.

Event listener with anonymous function

Why use addeventlistener .

addEventListener is the way to register an event listener as specified in W3C DOM. The benefits are as follows:

  • It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well with other libraries/extensions.
  • It gives you finer-grained control of the phase when the listener is activated (capturing vs. bubbling).
  • It works on any DOM element, not just HTML elements.

The alternative, older way to register event listeners , is described below.

Adding a listener during event dispatch

If an EventListener is added to an EventTarget while it is processing an event, that event does not trigger the listener. However, that same listener may be triggered during a later stage of event flow, such as the bubbling phase.

Multiple identical event listeners

If multiple identical EventListener s are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener method.

The value of this within the handler

It is often desirable to reference the element on which the event handler was fired, such as when using a generic handler for a set of similar elements.

If attaching a handler function to an element using addEventListener() , the value of this  inside the handler is a reference to the element. It is the same as the value of the  currentTarget property of the event argument that is passed to the handler.

If an event attribute (for example, onclick ) is specified on an element in the HTML source, the JavaScript code in the attribute value is effectively wrapped in a handler function which binds the value of this  in a manner consistent with the addEventListener() ; an occurrence of  this within the code represents a reference to the element. Note that the value of this inside a function, called by  the code in the attribute value, behaves as per standard rules . This is shown in the following example:

The value of this within modifyText(), when called via the onclick event, is a reference to the global ( window ) object (or undefined in the case of strict mode ).

This is an example with and without bind :

A problem in the example above is that you cannot remove the listener with bind . Another solution is using a special function called handleEvent to catch any events:

Another way of handling the reference to this is to pass to the EventListener a function that calls the method of the object which contains the fields that need to be accessed:

Legacy Internet Explorer and attachEvent

In Internet Explorer versions before IE 9, you have to use attachEvent , rather than the standard addEventListener . For IE, we modify the preceding example to:

There is a drawback to attachEvent:  The value of this will be a reference to the window object, instead of the element on which it was fired.

Compatibility

You can work around addEventListener() , removeEventListener() , Event.preventDefault(), and Event.stopPropagation() not being supported by IE 8 by using the following code at the beginning of your script. The code supports the use of handleEvent and also the DOMContentLoaded event.

Note: useCapture is not supported, as IE 8 does not have any alternative method. The following code only adds IE 8 support. This IE 8 polyfill only works in standards mode: a doctype declaration is required.

Older way to register event listeners

addEventListener() was introduced with the DOM 2 Events specification. Before then, event listeners were registered as follows:

This method replaces the existing click event listener(s) on the element if there are any. Other events and associated event handlers such as blur ( onblur ) and keypress ( onkeypress ) behave similarly.

Because it was essentially part of DOM 0, this technique for adding event listeners is very widely supported and requires no special cross–browser code. It is normally used to register event listeners dynamically unless the extra features of addEventListener() are needed.

Memory issues

In the first case, a new (anonymous) function is created with each iteration of the loop. In the second case, the same previously declared function is used as an event handler. This results in smaller memory consumption. Moreover, in the first case, it is not possible to call removeEventListener() because no reference to the anonymous function is kept. In the second case, it's possible to do myElement.removeEventListener("click", processEvent, false) .

The default value for the passive option is false . Starting in Chrome 56 (desktop, Chrome for Android, and Android webview) the default value for touchstart and touchmove is true and calls to preventDefault() are not permitted. To override this behavior, you set the passive option to false as shown in the example below. This change prevents the listener from blocking page rendering while a user is scrolling. A demo is available on the Google Developer site. Please note that Edge does not support the options  argument at all, and adding it will prevent the use of the useCapture  argument.

Setting passive  isn't important for the basic scroll event, as it cannot be canceled, so its listener can't block page rendering anyway.

Specifications

Browser compatibility.

[1] Although WebKit has explicitly added [optional] to the useCapture parameter as recently as June 2011 , it had been working before the change. The new change landed in Safari 5.1 and Chrome 13.

[2] Before Chrome 49, the type and listener parameters were optional.

[3] Before Firefox 6, the browser would throw an error if the useCapture parameter was not explicitly false . Before Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6), addEventListener() would throw an exception if the listener parameter was null ; now the method returns without error, but without doing anything.

[4] Older versions of Internet Explorer support the proprietary EventTarget.attachEvent method instead.

[5] For backward compatibility, browsers that support  options allow the third parameter to be either options or Boolean .

  • EventTarget.removeEventListener()
  • Creating and triggering custom events
  • More details on the use of this in event handlers

Document Tags and Contributors

  • EventTarget
  • addEventListener()
  • attachEvent()
  • detachEvent()
  • dispatchEvent()
  • via fireEvent() will not toggle the checkedness of the checkbox.'> fireEvent()
  • removeEventListener()
  • beforeinput
  • compositionstart
  • compositionupdate
  • compositionend
  • CompositionEvent
  • EventListener
  • KeyboardEvent
  • MouseScrollEvent
  • MouseWheelEvent
  • MutationEvent
  • ProgressEvent

JS Reference

Html events, html objects, other references, html dom document addeventlistener().

Add a click event to the document:

Simpler syntax:

More examples below.

Description

The addEventListener() method attaches an event handler to a document.

Element Methods

The addEventListener() Method

The removeEventListener() Method

Document Methods

HTML DOM EventListener

The Complete List of DOM Events

Return Value

Advertisement

More Examples

You can add many event listeners to the document:

You can add different types of events:

When passing parameters, use an "anonymous function" to call a function with the parameters:

Change the background color of the document:

Using the removeEventListener() method:

Browser Support

document.addEventListener is a DOM Level 2 (2001) feature.

It is fully supported in all browsers:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Introducing the Dialog Element

Feb 7, 2022

by Tim Nguyen

@therealntim

Although the alert , confirm and prompt JavaScript methods are convenient, they aren’t recommended due to their script-blocking behavior. That’s why we worked with other browser vendors to drive improvements to the <dialog> specification over the last few years. The most important conversations involved accessibility.

You can find more complex use-cases, like payment dialogs, on the web. They are currently addressed by custom solutions from frameworks like Bootstrap. Unfortunately, they aren’t convenient to use and aren’t always accessible. We believe the web deserves a simple and bug-free solution for these use-cases. Safari Technology Preview 134 and Safari 15.4 beta introduces the <dialog> element for this reason!

How Do I Use <dialog> ?

Let’s create a simple confirmation dialog:

Dialogs are hidden by default. We can use the showModal() method to show the dialog. When it’s shown, the dialog can be closed with the close() method.

Here is an example:

Note that the dialog will get an open attribute once opened, which may be useful for styling purposes. However, it’s not recommended to toggle this attribute manually to show or hide the dialog, since the browser may lose track of the dialog state, and will not perform proper focus adjustments for accessibility.

Modal and Non-modal Dialogs

In the last example, the showModal() method was used to create a modal dialog. User interaction is locked inside modal dialogs and outside content cannot be clicked, focused, selected, edited, or seen by accessibility tools. Another feature of modal dialogs is their ability to appear on top of everything else in the web page, regardless of the z-index of other elements.

Non-modal dialogs also exist and can be invoked using show() method. Unlike modal dialogs, they still allow interaction with the surrounding content. An example use-case may be a find-in-page dialog for a document editor, where you still want to allow the user to interact with the rest of the document.

Using Forms with <dialog>

Forms within dialogs can be used to request information from the user, such as when a shipping address or payment details are needed.

Unlike a traditional <form> , where method="get" or "post" indicates that the form data is sent to a server, using <form method="dialog"> causes form submission instead to close the dialog and set the returnValue property to the submit button’s value. This can save you from writing custom code, while providing the correct semantics to your web page.

We can simplify the initial example using this new feature:

Note the use of the close event here, which is special to <dialog> .

The semi-transparent box behind the dialog that you may have noticed from previous examples is the ::backdrop pseudo-element. By default, it is styled so it covers the whole viewport. Like the dialog itself, you can style the backdrop using CSS. Animations can also be used if you would like to add a fade-in effect for instance.

Note that the backdrop is only shown for modal dialogs.

This is a pretty dialog

The backdrop animates!

Accessibility

For accessibility tools, the <dialog> element is equivalent to role="dialog" . In addition to that, a modal dialog will behave similarly to an element with aria-modal="true" .

Users can dismiss modal dialogs using the “Escape” key on desktop browsers. That will trigger a cancel event which you can intercept. If multiple modal dialogs are opened, the one shown last will be dismissed.

It is also possible to specify an element to initially focus on when opening dialogs by adding the autofocus attribute to the relevant element.

Browser Support

  • Safari 15.4 beta and Safari Technology Preview

In this post, we’ve covered the basics of <dialog> and the features around it. Here are the next steps around this element:

We are working on getting the element interoperable with other browser vendors as part of the Interop 2022 effort. One of the main discussions is around initial focus behaviour , to agree on which elements should be focused by default when there is no element with the autofocus attribute.

As part of implementing <dialog> we’ve also made advances on the inert attribute to get interoperable behavior across browsers. It is currently disabled by default and not yet standardized, but you can enable the “inert attribute” in the Experimental Features menu from the Develop menu in Safari Technology Preview to test it.

Feel free to reach out to @therealntim on Twitter for any questions. To report any issues, please file a bug blocking bug 84635 .

[FIXED] addEventListener click not working

Understanding Event Listeners in JavaScript - fixing addEventListener issues

🔔 Table of contents

Introduction.

The reasons why addEventListener click not working on your website could be:

  • Element does not exist at script execution
  • Selector is incorrect
  • Not using addEventListener correctly
  • Click event is being prevented by another code
  • The element is not interactive and will not accept addEventListener
  • Fix other Javascript errors on the page

When I was working on a old web design, I had to do this feature where the user clicks on this button and a overlay would appear.

I have tried working with “addEventListener” function but no idea why it is not working.

In the end I found that my selector is not right - I was targeting the wrong element!

In this post, I will go over my troubleshooting checklist to deal with this issue.

1. Element does not exist

One thing that could trip you up is that the element you are adding the “addEventListener” function to does not exist at the time of the script execution.

Generally this happens when you have scripts that run too early (top of the HTML page) or that you have dynamic elements.

One way to get around this is to use the DOMContentLoaded handler:

Alternatively, you can place your <script> at the end of the HTML page and also use the defer attribute:

<script src="demo_defer.js" defer></script>

This ensures that it is executed AFTER the page has finished parsing!

Keep in mind that there are some things you will have to keep in mind when working with defer scripts:

  • Deferred scripts wait for stylesheets to load before executing.
  • DOMContentLoaded event is queued after the execution of deferred scripts.
  • Scripts that are not deferred or async (e.g., using a regular <script> tag) wait for already-parsed stylesheets to load before executing.

2. Selector is incorrect

A common mistake is that you are not targeting the right element - D’oh!

For example, some of my mistakes previously:

3. Not using addEventListener correctly

Another common issue is not using “addEventListener” correctly.

The specifications state that the function will only work for elements that support events.

The syntax will look like this:

addEventListener(type, listener, options)

  • type is a string of a “event type” and case-sensitive. So this means that ‘Click’ (and will not work) is different to ‘click’. You can see all possible event types here: Events
  • listener is a function reference.

A common way to use “ addEventListener ” is as follows:

What can trip you up is that the “listener” parameter has to be a function REFERENCE - and not function CALL

So to understand this - lets consider we have a function addTodo and we want to be called everytime someone clicks your button.

The proper way to do this is:

However, if you write addTodo() - notice the extra brackets () :

addTodo() is executed immediately - and this is not the behavior we want. Since addTodo() will execute immediately and will not trigger when someone clicks your button!

4. Click event is being prevented by another code

This might be a bit tricker to fix since it will involve you looking throughout the codebase.

Generally, you want to check if there’s another addEventListener that’s preventing the propagation of the event (using event.stopPropagation() or event.stopImmediatePropagation()), then the click event may not be triggered.

5. The element is not interactive and will not accept addEventListener

The addEventListener does not accept all HTML elements. It only accepts elements that support interactive events. For example, <span> tags and <div> tags don’t inherently respond to click events unless they have a tabindex or explicit role attribute indicating they should be interactive.

In HTML, only certain elements are naturally interactive and can receive focus (and subsequently, certain events).

For example, anchor ( <a> ), button ( <button> ), and input ( <input> ) elements are naturally interactive, meaning they can be focused on and clicked. They can naturally receive ‘click’ events, keyboard events like ‘keypress’, ‘keydown’, ‘keyup’, etc.

Non-interactive elements like <param> , <head> , <title> , <script> , <track> , <code> , etc., are not naturally focusable or interactive. They do not naturally receive these same events.

6. Fix other Javascript errors on the page

If you have other JavaScript errors prior to the addEventListener in your code, they could be stopping your script from executing further, including the part where you add the event listener.

JavaScript will stop executing code at the point where it encounters an unhandled error.

Generally, I would look at the browser console to see if theres any errors that pops up. Make sure to fix those errors first.

Somethings that tripped me up in the past includes:

  • Not matching opening and closing brackets
  • Incorrect variable or function names (JavaScript is case-sensitive)
  • Accessing a variable that has not been defined
  • Trying to access properties or methods on null or undefined - could be result of failed CORS or AJAX calls.

Keep in mind that the order of the scripts in your HTML file matters.

Make sure that any dependencies (like libraries or other custom scripts) are loaded before your script.

Also, ensure your DOM elements are loaded before trying to access them by running your code inside a DOMContentLoaded event handler, or by placing your script tags right before the closing tag.

Browser compatibility

IE<=8 instead only supports the proprietary .attachEvent() method. It also does not support the capture phase of DOM event dispatch; it only supports event bubbling.

The useCapture parameter is non-optional and must be provided. Future versions made it optional, with a default value of false.

Tips for using addEventListener When you are using anonymous functions to as handlers, keep in mind of memory issues. Repeatedly assigning a anonymous function to the same element will cause memory to blow out since Javascript will treat these functions differently. Make sure you also use the “removeEventListener” where possible. This way we do not have so many handlers hanging around and slowing down your app. addEventListener is the recommended way to handle events for HTML elements due to its wide support and ability to remove handlers when not needed. Other options include the “onclick” handlers, but not generally recommended!

In this post we went over the reasons why addEventListener click not working on your website. There are multiple reasons why addEventListener could not be working and we can use the following checklist to troubleshoot:

  • Make sure the element does exist at script execution - this can trip you up since you are attaching to a null object.
  • Verify that your target selector is correct - it needs to be a HTML element that accepts interactive events
  • Check the syntax for addEventListener - the “type” is case sensitive, and “handler” must be a function reference
  • Check that your handler is not being prevented by another code
  • Make sure that the element is interactive and will accept addEventListener events

👋 About the Author

G'day! I am Huy a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.

My aim to share what I have learnt with you! (and to help me remember 😅)

Follow along on Twitter , GitHub and YouTube

👉 See Also 👈

  • 8 Ways to Convert JavaScript Object to String
  • [SOLVED] ERR_MODULE_NOT_FOUND - Cannot find module.md
  • How to capitalize first letter in JavaScript

The Firebase Blog

Sending to macos, ios safari using fcm js sdk.

Kai Wu

Developers! Firebase Cloud Messaging now supports notifications on Safari. Thanks to Apple’s support for the Push API from Safari 16.1 and macOS 16.4 iOS & iPadOS, you can now send Firebase Cloud Messaging notifications to your web applications served on these versions of Safari. This opens up new possibilities for engaging with your users and enhancing the user experience and complements the wide range of existing platforms supported such as Chrome and Edge browsers

In this blog post, we’ll provide an overview of how to enable web push notifications for Safari using Firebase Cloud Messaging. We’ll cover everything you need to know including code snippets for critical setup and configuration.

By following these steps, you’ll be able to send push notifications to your users on Safari and enhance their experience with your app. Let’s dive in and explore how to take advantage of this new feature!

How to Enable Firebase Cloud Messaging on Safari for macOS

Enabling Firebase Cloud Messaging for Safari on macOS requires just a few steps. To get started, we recommend checking out the Firebase FCM JS SDK quick start guide on GitHub. It’s an out-of-the-box sample app that works on most browsers including Safari. This guide provides a detailed walkthrough for setting up Firebase Cloud Messaging in your web app and a code sample that you can use as a starting point.

To enable the Push API for Safari, make sure to wrap the requestPermission() API inside a user action, such as a button click.

By enabling web push notifications for Safari, you’ll be able to increase engagement with your users, improve the user experience, and increase visibility and awareness for your app. And that’s it!

How to Enable Firebase Cloud Messaging on Safari for iOS and iPadOS

Enabling Firebase Cloud Messaging for Safari on iOS and iPadOS requires some additional steps beyond those required for macOS.

Configure the manifest.json file

Configure your web application to set “display”: “standalone” or “fullscreen” in the manifest.json file, which allows your app to be added to the Home Screen.

Add to home screen

Prompt users to add your app to the home screen. It’s a requirement to add the app to the home screen for push notifications. Once users install your app on the home screen, it will receive push notifications.

Adding a progressive web application (PWA) on Safari iOS to the Home Screen

Request push notification permissions

Request permission to receive push notifications in response to direct user interaction, such as tapping on a ‘subscribe’ button provided by the web app.

Initialize FCM

Now that we have the user’s permission let’s initialize Firebase Cloud Messaging by adding the following code snippet to your JavaScript:

Sending notifications

Now you can send a notification to the application either through v1 Send API (below we show a code snippet) or the Firebase console.

To learn more about sending through the Firebase console, please refer to https://firebase.google.com/docs/cloud-messaging/js/send-with-console

By following these steps, you can enable web push notifications for Safari on iOS and iPadOS using Firebase Cloud Messaging.

APNs & FCM

It’s important to note that web push on iOS and iPadOS uses the same Apple Push Notification service that powers native push on all Apple devices. You don’t need to be a member of the Apple Developer Program to use it, but be sure to allow URLs from *.push.apple.com if you control your server push endpoints.

Enabling web push notifications for Safari on both macOS and iOS/iPadOS using Firebase Cloud Messaging is now possible with recent updates from Apple adding support for the Push API in Safari. With Firebase Cloud Messaging, you can increase engagement, enhance user experience, and increase the visibility for your app. Follow the steps outlined in this post and reference the Firebase FCM JS SDK quick start guide on GitHub to get started. Contact the Firebase community if you need help or have feedback. We’re here to help you on your development journey.

IMAGES

  1. addEventListener

    safari support for addeventlistener

  2. JavaScript Getting Started

    safari support for addeventlistener

  3. How to use addEventlistener in JavaScript tutorial for Beginners

    safari support for addeventlistener

  4. addEventListener, object with a handleEvent() method support. · Issue

    safari support for addeventlistener

  5. HTML

    safari support for addeventlistener

  6. mobileQuery.addEventListener is undefined in Safari · Issue #28798

    safari support for addeventlistener

VIDEO

  1. addEventListener()

  2. How to use Safari on iPhone

  3. addEventListener JavaScript

  4. Running Safari 16 on Windows is EASY!!!

  5. React 18 Tutorial

  6. How To Create and Use Safari Web Apps On Your Mac

COMMENTS

  1. addEventListener

    Messaging Support. To navigate the symbols, press Up Arrow, Down Arrow, Left Arrow or Right Arrow . C. ... void addEventListener ( in DOMString type, in Safari Event Listener listener, in boolean useCapture); Parameters type. The type of event to listen for.

  2. window.addEventListener("message", getData); doesn't work in safari?

    it seems like safari dont have the full support but it should support if you check the browser support of addEventListener you can see. options.passive parameter defaults to true for touchstart and touchmove events. options.passive parameter defaults to true for wheel and mousewheel events. options.signal parameter.

  3. addEventListener

    Support; Account; Cancel . Only search within ... Safari Desktop, Safari Mobile. void addEventListener ( DOMString type, Event Listener? callback, optional ); Current page is addEventListener

  4. EventTarget: addEventListener() method

    It works on any event target, not just HTML or SVG elements. The method addEventListener() works by adding a function, or an object that implements a handleEvent() function, to the list of event listeners for the specified event type on the EventTarget on which it's called. If the function or object is already in the list of event listeners for ...

  5. Handling Events

    This chapter describes the events that occur when the user interacts with a webpage on iOS. Forms and documents generate the typical events in iOS that you might expect on the desktop. Gestures handled by Safari on iOS emulate mouse events. In addition, you can register for iOS-specific multi-touch and gesture events directly.

  6. addEventListener() does not work well on Safari #13929

    Bug report Describe the bug. In development mode, the console.log() (see just below) is done on Firefox, but not on Safari.In production mode, the console.log() is displayed on both browsers.. To Reproduce. Put an event listener in the componentDidMount() of your React class component.

  7. EventTarget.addEventListener() Browser Compatibility On Safari

    addeventlistener property shows High browser compatibility on Safari browsers. High browser compatibility means the addeventlistener property is Fully Supported by a majority of Safari browser versions. Review us on Gartner Peer Insights and win a voucher worth $25. Claim Now .

  8. addEventListener is not working in safari iPhone

    Safari suggestions doesn't work My iPhone 13 running iOS 15 doesn't come up with suggestions when you start typing in safari. This happens about 95% of the time. Very rarely it will work so I am doubtful it is anything to do with the settings.

  9. Using AbortController as an Alternative for Removing Event Listeners

    Again, Chrome 88 is currently the only place where addEventListener officially accepts an AbortSignal. While other major browsers, including Firefox and Safari, support AbortController, integrating its signal with addEventListener is a no go at the moment… and there are no signals (pun sorta intended) that they plan to work on it. That said, a polyfill is available.

  10. EventTarget.addEventListener()

    The EventTarget method addEventListener() sets up a function that will be called whenever the specified event is delivered to the target. Common targets are Element, Document, and Window, but the target may be any object that supports events (such as XMLHttpRequest).. addEventListener() works by adding a function or an object that implements EventListener to the list of event listeners for the ...

  11. Browser Compatibility of EventTarget.addEventListener ()

    EventTarget.addEventListener() shows a browser compatibility score of 100. This is a collective score out of 100 to represent browser support of a web technology. The higher this score is, the greater is the browser compatibility. The browser compatibility score is not a 100% reflection for every browser and the web technology support.

  12. EventTarget.addEventListener()

    The EventTarget.addEventListener() method adds the specified EventListener -compatible object to the list of event listeners for the specified event type on the EventTarget on which it is called. The event target may be an Element in a document, the Document itself, a Window, or any other object that supports events (such as XMLHttpRequest ).

  13. HTML DOM Document addEventListener() Method

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

  14. Introducing the Dialog Element

    Browser Support. Safari 15.4 beta and Safari Technology Preview; Chrome 37; Firefox 98; Next Steps. In this post, we've covered the basics of <dialog> and the features around it. Here are the next steps around this element: We are working on getting the element interoperable with other browser vendors as part of the Interop 2022 effort.

  15. [FIXED] addEventListener click not working

    3. Not using addEventListener correctly. Another common issue is not using "addEventListener" correctly. The specifications state that the function will only work for elements that support events. The syntax will look like this: addEventListener(type, listener, options) type is a string of a "event type" and case-sensitive. So this ...

  16. javascript

    The fx_Hello function when called inside the addEventListener with the "click" event, returns an alert PopUp to appear whenever I click on any part of the HTML page or Elements of the page. In Chrome and Mozzila browsers it's working perfectly, but in Safari browser for IOS, the PopUp is only appearing if you click on the link with the id some_ID.

  17. Sending to MacOS, iOS Safari using FCM JS SDK

    August 1, 2023. Developers! Firebase Cloud Messaging now supports notifications on Safari. Thanks to Apple's support for the Push API from Safari 16.1 and macOS 16.4 iOS & iPadOS, you can now send Firebase Cloud Messaging notifications to your web applications served on these versions of Safari. This opens up new possibilities for engaging ...

  18. Safari Extension

    I'm porting my Chrome extension into Safari, and I've encountered a little issue I would like to ask about. ... Safari Extension - Addeventlistener click not working. Ask Question Asked 6 years, 4 months ago. Modified 6 years, 4 months ago. Viewed 2k times 0 I'm porting my Chrome extension into Safari, and I've encountered a little issue I ...