I couldn't find any answer so I'm asking here. Currently I don't own any touch devices so I can't test it.
The following code hides all subcontainers in a container if clicked outside of it.
$(document).mouseup(function(e) {
var container = $('#container');
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
$('.subcontainer').hide();
}
});
Does this work on touch devices or there is any equivalent of mouseup
for touch devices?
This works swimmingly on the desktop, but on mobile (testing in iOS Safari), the mousedown and mouseup events happen at the same time, so effectively nothing happens.
jQuery mouseup() Method The mouseup event occurs when the left mouse button is released over the selected element. The mouseup() method triggers the mouseup event, or attaches a function to run when a mouseup event occurs. Tip: This method is often used together with the mousedown() method.
The mouseup event is fired at an Element when a button on a pointing device (such as a mouse or trackpad) is released while the pointer is located inside it. mouseup events are the counterpoint to mousedown events.
Note: This differs from the click event in that click is fired after a full click action occurs; that is, the mouse button is pressed and released while the pointer remains inside the same element. mousedown is fired the moment the button is initially pressed.
No, it does not work. But here is a touchstart
and touchend
event.
$(document).bind( "mouseup touchend", function(e){
var container = $('#container');
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
$('.subcontainer').hide();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With