Make onclick work on iphone

This post got more attention, so I'm going to add another commonly used, more up to date, trick:

// First we check if you support touch, otherwise it's click:
let touchEvent = 'ontouchstart' in window ? 'touchstart' : 'click';

// Then we bind via thát event. This way we only bind one event, instead of the two as below
document.getElementById('hbs').addEventListener(touchEvent, someFunction);

// or if you use jQuery:
$('#hbs').on(touchEvent, someFunction);

The let touchEvent should be declared out of function (also not in a document.ready) at the top of your javascript. This way you can use this in all your javascript. This also allows easy (jQuery) usage.


Old answer:

This fixes the need for copying your code (well at least to a minimum). Not sure if you can combine them

function someFunction() {
    alert('element was clicked');
}

document.getElementById('hbs').onclick = someFunction;
document.getElementById('hbs').ontouchstart= someFunction;

document.getElementById('hbs')
    .addEventListener('click', someFunction)
    .addEventListener('touchstart', someFunction);

Tags:

Javascript