6

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?

Mark
  • 2,380
  • 11
  • 29
  • 49

4 Answers4

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);
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
  • 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? – Mark Dec 27 '12 at 14:53
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', () => {})`
mcmimik
  • 1,389
  • 15
  • 32
1

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

  • I tried replacing "click" with "click touchstart" but that breaks the code completely. Are you sure that this would be correct? – Mark Dec 27 '12 at 14:57
  • 1
    I think this reply was in context of jQuery. This might help: http://stackoverflow.com/questions/11845678/adding-multiple-event-listeners-to-one-element – escapedcat Jul 04 '16 at 03:56
  • addEventListener only accepts a single event, it doesn’t work like jQuery. – LeBen Feb 27 '17 at 08:53
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.

Mark
  • 2,380
  • 11
  • 29
  • 49