Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make onclick work on iphone

Tags:

javascript

I have been using "onclick" in my javascript, but now I want it to work on Iphone as well. Is there a simple way to make all "onclick" to work like ontouchstart for devices that support ontouchstart?

Or do I need to write all script twice (one that uses onclick and one that uses ontouchstart)? :S

Note: I dont want to use jquery or any other library.

<!DOCTYPE html>
<title>li:hover dropdown menu on mobile devices</title>
<script>
window.onload = function () {
    if ('ontouchstart' in window) {
        // all "onclick" should work like "ontouchstart" instead
    }
    document.getElementById('hbs').onclick = function () {
        alert('element was clicked');
    }
}
</script>
<a id=id1 href=#>button</a>
like image 461
user1087110 Avatar asked Sep 20 '13 10:09

user1087110


1 Answers

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);
like image 77
Martijn Avatar answered Oct 18 '22 06:10

Martijn