Click event listener works in Safari in OSX but not in iOS
Asked Answered
B

4

7

I'm making a web app and I want to click on an element and handle the click in one long click event handler. I'm testing in Safari. The following works fine in Safari on my Mac but not in iOS:

<html>
    <head>
        <script>
            window.addEventListener("click",function (event) {
                alert('hi');
            });
        </script>
    </head>
    <body>
        <div style="width: 100%; height: 100%; background: black;">
        </div>
    </body>
</html>

Why does this work in the OSX version of Safari but not in iOS?

Balloon answered 27/12, 2012 at 11:54 Comment(0)
B
0

I found a very simple solution. I put another div about the div element in my sample code (see my question above). The opening div tag is

<div onClick="">

All divs inside this div tag will now trigger the click event. This also works with touchstart.

Balloon answered 27/12, 2012 at 16:47 Comment(0)
S
3

This code should work cross-browser:

function Subscribe(event, element, func) {
    if (element.addEventListener) {
        element.addEventListener(event, func, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + event, func);
    } else {
        element['on' + event] = func;
    }
}

function func () {
    alert('hi');
}

Subscribe('click', window, func);
Scotney answered 27/12, 2012 at 11:58 Comment(1)
I don't need a cross-platform solution. I need it to work in Safari. If I remove everything that isn't for Safari from your code and rewrite it to be less verbose then I get exactly the same as my original code, which doesn't work. Do you have any different ideas?Balloon
M
2

In my case I just needed to replace window to document:

Doesn't work on iOS:

window.addEventListener('click', () => {})

iOS compatible:

document.addEventListener('click', () => {})`
Meganmeganthropus answered 28/6, 2021 at 13:40 Comment(0)
T
1

Try changing the event listener "click" to "click touchstart"

Thetisa answered 27/12, 2012 at 13:45 Comment(3)
I tried replacing "click" with "click touchstart" but that breaks the code completely. Are you sure that this would be correct?Balloon
I think this reply was in context of jQuery. This might help: #11846178Proem
addEventListener only accepts a single event, it doesn’t work like jQuery.Pleiades
B
0

I found a very simple solution. I put another div about the div element in my sample code (see my question above). The opening div tag is

<div onClick="">

All divs inside this div tag will now trigger the click event. This also works with touchstart.

Balloon answered 27/12, 2012 at 16:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.