16

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>
user1087110
  • 3,633
  • 11
  • 34
  • 43

2 Answers2

26

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);
Martijn
  • 15,791
  • 4
  • 36
  • 68
  • 1
    I would invert it and do `var touchEvent = 'onclick' in window ? 'click' : 'touchstart';`. Otherwise for touch screen laptops the click wouldn't work. – Richard Williams Jan 15 '17 at 14:24
  • If you do that, ontouch might not work when someone touches the screen. I suggest you test on a dummy code and place the results here – Martijn Jan 16 '17 at 08:04
  • 1
    Yes you're right. Though after a bit more digging around it seems that the click event works on iphones provided the element in question has `cursor: pointer` set on it http://stackoverflow.com/a/4910962/596639. – Richard Williams Jan 16 '17 at 21:56
-7

The reason javascript is not working on the iPhone in Safari is because iPhones have the option to turn off Javascript.

Go to "Settings" Then scroll down to "Safari" Then scroll all the way to the bottom "Advanced" Then turn on Javascript!

Also, you can check if Javascript is enabled with this code:

<script type="text/javascript">
   document.write("Javascript is working.")
</script>

<noscript>JavaScript is DISABLED!!!!!!</noscript>