Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document .click function for touch device

Tags:

jquery

css

I've got a sub-nav that works using jquery - A user clicks on the top level list item, for instance 'services' which triggers the dropdown. The dropdown toggles via clicking the 'service' link. I've made it so a user can click anywhere on the screen to toggle the dropdown to a closed state. But as the site is responsive i want the user to be able to click (touch) anywhere on the screen to close the dropdown but my problem is that it's not working on the touch devices.

My code ive setup for the document click is:

$(document).click(function(event) {     if ( $(".children").is(":visible")) {     $("ul.children").slideUp('slow');   }  }); 

I'm assuming document.click might not work on touch devices, and if not, what work-around is there to achieve the same effect?

Thanks

like image 556
Doidgey Avatar asked Jul 09 '12 14:07

Doidgey


People also ask

Does Onclick work for touch?

onclick may not work on touch devices, I had this issue and the event ontouchstart sorts it. if you use ontouchstart and onclick watch that you don't trigger the event twice. Show activity on this post. Pro tip: If you want to test the touch event in development, use Chrome following this.

What is the difference between .on click function ()) and .click function?

So onclick creates an attribute within the binded HTML tag, using a string which is linked to a function. Whereas . click binds the function itself to the property element.

Does click event work on mobile?

click() is not working on some Android devices (it works but have to click twice…) this is for standard nav show/hide that is used in mobile devices…


1 Answers

Update! In modern browsers, the click event will be fired for a tap, so you don't need to add extra touchstart or touchend events as click should suffice.

This previous answer worked for a time with browsers that thought a tap was special. It originally included a "touch" event that actually was never standardised.

Unless you have a problem with:

$(document).on('click', function () { ... }); 

There is no need to change anything!

Previous information, updated to remove touch...

To trigger the function with click or touch, you could change this:

$(document).click( function () { 

To this:

$(document).on('click touchstart', function () { 

The touchstart event fires as soon as an element is touched, so it may be more appropriate to use touchend depending on your circumstances.

like image 61
Fenton Avatar answered Sep 20 '22 03:09

Fenton