Make Onclick Work On Iphone
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 su
Solution 1:
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'inwindow ? 'touchstart' : 'click';
// Then we bind via thát event. This way we only bind one event, instead of the two as belowdocument.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
functionsomeFunction() {
alert('element was clicked');
}
document.getElementById('hbs').onclick = someFunction;
document.getElementById('hbs').ontouchstart= someFunction;
document.getElementById('hbs')
.addEventListener('click', someFunction)
.addEventListener('touchstart', someFunction);
Solution 2:
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:
<scripttype="text/javascript">document.write("Javascript is working.")
</script><noscript>JavaScript is DISABLED!!!!!!</noscript>
Post a Comment for "Make Onclick Work On Iphone"