Question on $(document).bind() - javascript

I have a page on iPad.
How do I get the specific element that was touched instead of the generic container element?
$(document).bind("touchstart",function(e){
console.log("touchstart on target : " + e.target.id);
}

Try using delegate instead
$(function() {
$(document).delegate('div', 'click', function(event) {
alert($(this).attr('id'));
// To prevent Propagation
event.stopPropagation()
});
});
in action: http://jsfiddle.net/xem65/
(Using click since I don't have any touch devices nearby atm)
Docs on delegate: http://api.jquery.com/delegate/

That seems like it should be working. Here is a small test case that logs out the event based off of http://gregmurray.org/ipad/touch-events.html, and it seems to recognize the touchstart happening on the div. Maybe you could post an example where it is failing?

Related

.addEventListener('click', classToggle) not working on touch devices [duplicate]

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
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.
touchstart or touchend are not good, because if you scroll the page, the device do stuff.
So, if I want close a window with tap or click outside the element, and scroll the window, I've done:
$(document).on('touchstart', function() {
documentClick = true;
});
$(document).on('touchmove', function() {
documentClick = false;
});
$(document).on('click touchend', function(event) {
if (event.type == "click") documentClick = true;
if (documentClick){
doStuff();
}
});
can you use jqTouch or jquery mobile ? there it's much easier to handle touch events.
If not then you need to simulate click on touch device, follow this articles:
iphone-touch-events-in-javascript
A touch demo
More in this thread
To apply it everywhere, you could do something like
$('body').on('click', function() {
if($('.children').is(':visible')) {
$('ul.children').slideUp('slow');
}
});
As stated above, using 'click touchstart' will get the desired result. If you console.log(e) your clicks though, you may find that when jquery recognizes touch as a click - you will get 2 actions from click and touchstart. The solution bellow worked for me.
//if its a mobile device use 'touchstart'
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
deviceEventType = 'touchstart'
} else {
//If its not a mobile device use 'click'
deviceEventType = 'click'
}
$(document).on(specialEventType, function(e){
//code here
});
the approved answer does not include the essential return false to prevent touchstart from calling click if click is implemented which will result in running the handler twoce.
do:
$(btn).on('click touchstart', e => {
your code ...
return false;
});

dropdown menu not working on mobile, document click not triggered [duplicate]

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
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.
touchstart or touchend are not good, because if you scroll the page, the device do stuff.
So, if I want close a window with tap or click outside the element, and scroll the window, I've done:
$(document).on('touchstart', function() {
documentClick = true;
});
$(document).on('touchmove', function() {
documentClick = false;
});
$(document).on('click touchend', function(event) {
if (event.type == "click") documentClick = true;
if (documentClick){
doStuff();
}
});
can you use jqTouch or jquery mobile ? there it's much easier to handle touch events.
If not then you need to simulate click on touch device, follow this articles:
iphone-touch-events-in-javascript
A touch demo
More in this thread
To apply it everywhere, you could do something like
$('body').on('click', function() {
if($('.children').is(':visible')) {
$('ul.children').slideUp('slow');
}
});
As stated above, using 'click touchstart' will get the desired result. If you console.log(e) your clicks though, you may find that when jquery recognizes touch as a click - you will get 2 actions from click and touchstart. The solution bellow worked for me.
//if its a mobile device use 'touchstart'
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
deviceEventType = 'touchstart'
} else {
//If its not a mobile device use 'click'
deviceEventType = 'click'
}
$(document).on(specialEventType, function(e){
//code here
});
the approved answer does not include the essential return false to prevent touchstart from calling click if click is implemented which will result in running the handler twoce.
do:
$(btn).on('click touchstart', e => {
your code ...
return false;
});

jQuery prevent function to duplicate on click

I want to initiate a plugin only if clicked on its parent element (because that element is being appended with jQuery so it does not exist when page loads), So I am trying following code:
$(document).on('click', '.wrap', function(){
ColorPicker(
document.getElementById('slider'),
document.getElementById('picker'),
function(hex, hsv, rgb) {
});
});
This works fine, but every time I click on the .wrap, it duplicates (please check the demo to see the problem). Is there anyway to fix it?
Demo:
http://jsfiddle.net/rhzzG/
(Click in the box to see the problem)
Thanks.
Rather than using on() to trigger this event every time the element is clicked, simply use jQuery's one() method to only fire it once:
$(document).one('click', '.wrap', function(){ ... });
ColorPicker will then take over from there with handling its own events.
JSFiddle demo.
You may use one instead
$(document).one('click', '.wrap', function(){
//...
});

Prevent child's onclick after mouseup on parent?

I have a parent element with mouse up and mouse down events attached on it, and a child element with a click event attached.
Is there any way to prevent the click event from happening in the child, after the mouseup event has been triggered in the parent?
An example, on the JSfiddle here, the goal is to make the inner square not turn to green if I click on it.
Ideally I would like to do it without modifying the $('#inner').on('click', function(){}). I already know that I can set a boolean on mouseup and check it on click but i'm trying to find a way to do it without modifying the click event.
Using jquery(or any other library) is option and I don't really have any restrictions other than not modifying the click method.
EDIT
Thanks #adeneo for the suggestion, that looks promising but it made me realize I missed a big part of the problem. Inside mouseup there will be a conditional check to see if the click should be prevented or not. If I remove the event can I somehow add it back after the click has been avoided? In a setTimeout for example. I'm not sure how(or if it's possible) to get the reference to the removed click function and then re-add the handler.
Hopefully this new fiddle here helps me to explain it a little bit better!
$('#inner').on('mouseup', function(e) {
$(this).unbind("click");
$(this).css({'background': 'black'});
});
Did you try like this?
Try e.stopImmediatePropagation(); in your inner code.
Just replace your code with the below code and check. To stop the click event of the inner div you can use preventDefault() or stopPropagation(). Please check below
$('#inner').on('click', function(e) {
$(this).stopPropagation();
// or
// $(this).preventDefault();
alert('inner click');
});
$('#outer').on('mousedown', function(e) {
$(this).css({'background': 'green'});
});
$('#outer').on('mouseup', function(e) {
$(this).css({'background': 'yellow'});
});
I'm pretty sure that this is the answer you're looking for :
$($(this)).children().click(function (event) { // Preveu la propagació del click als fills
// event.stopPropagation();
});

How do I unbind events properly when using allowSamePageTransition in jQuery Mobile?

I'm using the jQuery Mobile option allowSamePageTransition, which enables me to go from
page A > page A > page A ...
I need this to allow browsing through a catalogue of items. My problem is, the items need some form of interaction and I used to attach the interaction binding to document, because it is set before the elements affected are generated.
However, reloading the same page over and over again will re-bind my event handlers every time I reload.
My first idea was to use .off when the page is being hidden, but reloading a page #foo, will trigger pagehide on the same page being shown, so all bindings set on
$(document).on("pagebeforeshow.foo_events", "#foo", function(e) {
// bind when shown
});
will be unbound again by the previous #foo being hidden
$(document).on("pagehide", "#foo", function (e) {
$(this).off(".foo_events");
// removes bindings on #foo being hidden AND shown
});
The only solution I have come up with is plastering the document with classes, which I don't like doing:
priv.setBindings = function (param) {
var doc = $(document);
doc
.filter(function() { return $(this).is(".e_gallery") !== true; })
.on("pagebeforeshow.gallery", param.pageId, function (e) {
doc.addClass(".e_gallery");
// run stuff
});
};
But I'm no fan of attaching classes to the dom.
Question:
Is there a way to prevent multiple event bindings set on $(document) when going to the same page over and over again WITHOUT toggling classes?
Solution 1
Best solution would be to use pageinit to bind events. If you take a look at an official documentation you will find out that pageinit will trigger ONLY once, just like document ready, so there's no way events will be bound again. This is best solution because you don't have processing overhead like when removing events with off method.
Working jsFiddle example: http://jsfiddle.net/Gajotres/AAFH8/
Of course this will fail in case multiple HTML solution is used.
Solution 2
Remove event before you bind it:
$(document).on('pagebeforeshow', '#index', function(){
$(document).off('click', '#test-button').on('click', '#test-button',function(e) {
alert('Button click');
});
});
Working jsFiddle example: http://jsfiddle.net/Gajotres/K8YmG/
Solution 3
Use a jQuery Filter selector, like this:
$('#carousel div:Event(!click)').each(function(){
//If click is not bind to #carousel div do something
});
Because event filter is not a part of official jQuery framework it can be found here: http://www.codenothing.com/archives/2009/event-filter/
This is probably best solution because event is going to be bound ONLY once.
Solution 4
Probably an easiest of them all.
$(document).on('pagebeforeshow', '#index', function(){
$(document).on('click', '#test-button',function(e) {
if(e.handled !== true) // This will prevent event triggering more then once
{
alert('Clicked');
e.handled = true;
}
});
});
Working jsFiddle example: http://jsfiddle.net/Gajotres/Yerv9/
This is a 180 percent different solution then solution 3, in this case event is going to be bound numerous times but it will be allowed to execute only once.
More info
If you want to find more about this problem take a look at this article, working examples are included.

Categories