Opera ignoring .live() event handler - javascript

I have the following jQuery which works in all major browsers except Opera:
jQuery(document).ready(function () {
jQuery("#GetResults").live("click", function(e){
e.preventDefault(); //Opera doesn't execute anything here
});
};
Which is supposed to fire when clicking the following link:
<a id="GetResults" href="Folder/File/javascript:void(0);">Get Results</a>
Only Opera ignores this. Any ideas?
Edit:
I've just discovered that if I substitute out .live() for .bind() everything functions as expected. I can't find any documentation relating to .live() bugs in Opera though, and it does work in jsFiddle which would point at something environmental. What could be causing this behavour?

This needs clarification. The answers above are correct, but nobody clearly explained where your problem comes from.
In fact I think that you could probably reproduce the problem in other browsers too.
That's because of how .live works:
It binds to the event on document and waits for a particular event to bubble up to there. Then it checks if the event.target is what you wanted to handle. *
If you click on a link element it's quite possible that the browser goes to the new page before the event bubbles high enough to trigger your code. In an app with lots of HTML and event handlers all the browsers should have problems. Opera just starts displaying the new page and destroys the previous quicker in this case. It really depends on a particular situation more than on the browser. For example: you probably won't see this happen if you had a high network latency while connecting to the site.
To prevent default action on a a element you have to use .bind like in the old days ;) when a eveloper had to be aware of what he loads with AJAX and bind new events to that in a callback.
* There is more to that and .live is more complicated. I just described what is needed here.

What happens when you attach the handler using:
$ (something).bind ("click", function (e) {
// do something
})
You can also try to attach the handler using .click() method.

The following code works as expected in Opera 11.50.
<!doctype html>
<title></title>
<a id="GetResults" href="http://google.com">Get Results</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
jQuery(document).ready(function () {
jQuery("#GetResults").live("click", function(e){
alert('doing something');
e.preventDefault(); //Opera doesn't execute anything here
});
});
</script>
Either it is a corrected bug, or something more subtle.
Can you check whether the above works on your version of Opera / jQuery?

Read this article: http://jupiterjs.com/news/why-you-should-never-use-jquery-live
try use delegate instead

Not sure if you want to do it, or if it will work for you. I had similar issues with Opera 9.5 and e.preventDefault() not working, the only solution I found was to just return false...
jQuery(document).ready(function () {
jQuery("#GetResults").live("click", function(e){
e.preventDefault();
return false;
});
};

There are two aspects of an event bubbling worth considering in this case: propagation and the default action.
Propagation refers to the event bubbling. First the anchor tag gets the click event, then its parent element, then its parent's parent, and so forth, up to the document element. You can stop an event from propagating at any time by calling e.stopPropagation().
The default action is what the browser will do if nothing is done to prevent it. The most well-known case is when an anchor with an href is clicked, the browser will try to navigate there. There are other examples too, though, for example when you click and drag an image, many browsers will create a ghost image you can drop on another application. In both cases, you can stop the browser from doing the default action at any time by calling e.preventDefault()
As mentioned in other answers to this question, jQuery's .live() feature sets a handler at a high level element (like document) and takes action after events have propagated up. If a handler in between the anchor and the document calls e.stopPropagaiton() without calling e.preventDefault() it would stop the live handler from responding, while still allowing the browser to navigate (the default action).
I doubt this is what's happening, since it would affect all browsers, but it's one possible explanation.

Ensure that document.ready event happens before you click on link.
Try to put all lives in the top of the document.ready wrapper. It may help, if you have a lot of javascript code.

Related

Is it possible to intercept/override all click events in the page?

I've written an html5 application which is supposed to work on mobile devices. 90% of the time it works fine however in certain devices (mostly androids 4.0+) the click events fire twice.
I know why that happens, I'm using iScroll 4 to simulate native scrolling and it handles the events that happen inside the scroll.(line 533 dispatches the event if you're interested) Most of the time it works fine but in certain devices both the iScroll dispatched event and the original onClick event attached to the element are fired, so the click happens twice. I can't find a pattern on which devices this happen so I'm looking for alternatives to prevent double clicks.
I already came up with an ugly fix that solves the problem. I've wrapped all the clicks in a "handleClick" method, that is not allowed to run more often than 200ms. That became really tough to maintain. If I have dynamically generated content it becomes a huge mess and it gets worse when I try to pass objects as parameters.
var preventClick = false;
function handleClick(myFunction){
if (preventClick)
return;
setTimeout(function(){preventClick = true;},200);
myFunction.call():
}
function myFunction(){
...
}
<div onclick='handleClick(myfunction)'> click me </div>
I've been trying to find a way to intercept all click events in the whole page, and there somehow work out if the event should be fired or not. Is it possible to do something like that?
Set myFunction on click but before it's called, trigger handleClick()? I'm playing with custom events at the moment, it's looking promising but I'd like to not have to change every event in the whole application.
<div onclick='myfunction()'> click me </div>
You can do that with the following ( i wouldn't recommend it though):
$('body').on('click', function(event){
event.preventDefault();
// your code to handle the clicks
});
This will prevent the default functionality of clicks in your browser, if you want to know the target of the click just use event.target.
Refer to this answer for an idea on how to add a click check before the preventDefault();
I don't like events on attributes, but that's just me.
Thinking jquery: $(selector).click(function(){ <your handler code> } you could do something like:
$(selector).click(function(event){
handleClick(window[$(this).attr("onclick")]);
};
of course, there wouldn't be any parameters...

Excessive Use of jQuery's preventDefault() and stopPropagation()

I was recently in a discussion with a work colleague about some differences in our coding practices, where I raised an issue about his excessive use of the two above mentioned methods in his event handlers. Specifically, they all look like this...
$('span.whatever').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
/* do things */
});
He has made the claim that this is a good practice with no foreseeable blowback, and will improve cross-platform support while reducing unexpected issues down the road.
My question to you guys: If he's right, why hasn't the jQuery team implemented this behavior globally applied to all event handlers? In effect, my assumption is that he's wrong simply because the methods are available for independent use, but who knows... Your insight is much appreciated.
--
Update: I did a simple speed test, and there is a little drag caused by these two function, but nothing terribly noticeable. Still, among other things, a good reason to be deliberate in their use I think.
$('span.whatever').on('click', function(e) {
var start = new Date();
for (i = 0; i < 999999; i++) {
e.preventDefault();
e.stopPropagation();
}
console.log( new Date() - start );
});
The above logged ~9.5 seconds as is, and ~2.5 seconds when I took the function calls out of the loop.
I don't do the same thing as your colleague (pushing the 2 calls on EVERY event handler), but I do have the same practice of using these calls explicitely rather than a "return false;", and I believe that has made my life easier.
When I started with Jquery, I figured if I need to both stop propagation, and prevent default, I should just "return false", which I kind of did all over the place.
$('a.whatever').on('click', function(e) {
do_stuff();
return false;
});
But there was 2 problems I enventually encountered:
if do_stuff() has any critical error causing an exception, "return false;" will never be reached!!! The error will eventually be "nicely" swallowed by jquery; your event will bubble, and let the browser execute the default action. If you are in a single page app and a link was clicked, for all you know the page navigated away, and the entire app state went down the toilet (I've been there before).
I was too lenient with my return false: in many cases, I just needed a preventdefault(). "return false" was killing event bubbling and sometimes hindered my ability to perform another action higher up the dom hierarchy (or made some other plugin/libs I was using not work properly)
So I now prefer to be explicit. I litterally never use "return false;" any more. If I have an event handler that must either not propagate or not execute default, I deliberatly put that in my function FIRST, before any processing code. Whatever happens during event handling should NOT affect the fact that I do NOT want the default action to run, and/or event to not bubble.
And yes, that being said, I am also mindful of using just one of the 2 when required (or none at all in some cases). I do not just add both preventDefault() and stopPropagation() for no reason. Everywhere I manipulate an event in a handler, it is part of a conscious case-by-case decision.
It would be a problem if the element is part of a menu and the click event was supposed to bubble out and tell the menu to close itself too.
Or if a menu was open elsewhere and clicking outside the menu was supposed to bubble up to the body where an event handler would close the menu. But the element having stopped the bubble, prevents the menu from closing.
<div id="wrapper">
<div id="header">header
<div id="footer">footer
<div id="content">click this!!!</div>
</div>
</div>
</div>
$("#wrapper div").click(function(){
console.log( $(this) )
});
Please try clicked to div and show console...
And now added
$("#wrapper div").click(function(e){
e.stopPropagation()
})

Weird click event behavior in IE8 with prototypejs 1.7_rc2

I have some javascript click handlers that don't do what I want in IE8. What I want to do is call a handler on the first click and then call another handler on all subsequent clicks. The way I do that is put the original handler in the onclick attribute and then use that handler to erase the onclick attribute and use Event#observe to set up the handler that is called on subsequent clicks but for some reason IE8 refuses to cooperate. Instead of the following program flow
click->call originalHandler->erase originalHandler->set newHandler
I get the unexpected program flow
click->call originalHandler->erase originalHandler->set newHandler->call newHandler
I can't figure out why a single click event fires both handlers. Here's the snippet of the offending code, the pastie link and a link to a page that consistently reproduces the bug on my laptop with ie8.
//weird behavior in the latest prototype version with ie8
function originalHandler(event) {
Event.stop(event); //this doesn't help either, the event still triggers newHandler
var button = $('button');
alert("first click");
button.writeAttribute({onclick:null});
function newHandler(event) {
//this should only show up on the second click
//but it shows up on the first click as well
alert('second click');
}
button.observe('click',newHandler);
}
So to get the desired behavior I have to add an extra layer of indirection which seems really weird. So the following code fixes the issue with IE8 but breaks firefox and chrome behavior because now "second click" doesn't show up until the third click. Here's the pastie for the version that works on IE8 and the link to the page that behaves correctly on IE8 but requires an extra click on chrome and firefox.
function originalHandler(event) {
Event.stop(event);
var button = $('button');
alert("first click");
button.writeAttribute({onclick:null});
var newHandler = function(ev) {
button.stopObserving();
button.observe('click',function() {alert("second click");});
}
button.observe('click',newHandler);
}
Any ideas on how to fix this bug and get consistent behavior across all browsers?
I also asked on the prototype mailing list and the answer I got was that basically what's happening is that IE8 calls the DOM0 handler and then calls DOM2 handlers which is what I set up with Element#observe and the way around it is to set up a delay so that the DOM2 handler is not set up until the first event bubbles all the way up without any DOM2 handlers in the way. Oh how I hate cross-browser compatibility.

jQuery live('click') firing for right-click

I've noticed a strange behaviour of the live() function in jQuery:
normal
live
$('#normal').click(clickHandler);
$('#live').live('click', clickHandler);
function clickHandler() {
alert("Clicked");
return false;
}
That's fine and dandy until you right-click on the "live" link and it fires the handler, and then doesn't show the context menu. The event handler doesn't fire at all (as expected) on the "normal" link.
I've been able to work around it by changing the handler to this:
function clickHandler(e) {
if (e.button != 0) return true;
// normal handler code here
return false;
}
But that's really annoying to have to add that to all the event handlers. Is there any better way to have the event handlers only fire like regular click handlers?
It's a known issue:
It seems like Firefox does not fire a
click event for the element on a
right-click, although it fires a
mousedown and mouseup. However, it
does fire a click event on document! Since .live catches
events at the document level, it sees
the click event for the element even
though the element itself does not. If
you use an event like mouseup, both
the p element and the document
will see the event.
Your workaround is the best you can do for now. It appears to only affect Firefox (I believe it's actually a bug in Firefox, not jQuery per se).
See also this question asked yesterday.
I've found a solution - "fix" the the live() code itself.
In the unminified source of jQuery 1.3.2 around line 2989 there is a function called liveHandler(). Modify the code to add one line:
2989: function liveHandler(event) {
2990: if (event.type == 'click' && event.button != 0) return true;
This will stop the click events from firing on anything but the left-mouse button. If you particularly wanted, you could quite easy modify the code to allow for "rightclick" events too, but this works for me so it's staying at that.
You can actually rewrite it as:
function reattachEvents(){
$(element).unbind('click').click(function(){
//do something
});
}
and call it when you add a new dom element, it should have the expected result (no firing on the right click event).
This is an unfortunate consequence of how live is implemented. It's actually uses event bubbling so you're not binding to the anchor element's click event, you're binding to the document's click event.
I solved this by using mousedown events. In my situation the distinction between mousedown and click didn't matter.

JQuery .click() event troubles

Here's a snippet of my code:
$(".item").click(function () {
alert("clicked!");
});
And I have (hypothetically; in actuality it's far more complicated) the following on my page:
<img src="1.jpg" />
However, when I click the image, I do not get an alert.
What is my mistake?
Is your selector actually matching anything? Try using the jQuery debug plugin (http://jquery.glyphix.com/) and doing this:
$(".item").debug().click(function() {
alert("clicked!");
});
.debug() will log whatever is matched to the Firebug console (you are using firebug, right? :-) ) without "breaking the chain" so you can use it inline like this.
If that turns out correctly, there may be some issue with the browser navigating to "#" before it can show your alert. Try using the .preventDefault() method on the event object to prevent this behavior:
$(".item").click(function(evt) {
evt.preventDefault();
alert("clicked!");
});
First question - are you adding the element to be clicked dynamically? If it is,
you should use the live event since that will take care dynamically created elements.
http://docs.jquery.com/Events/live#typefn
Use bind.
$(".item").bind("click", function(e) { ... });
modifying the selector?
$(".item > img")
I had this problem recently after adding a context menu jquery plugin. The pluging was binding to the click event of the body and then unbinding click event - it seemed to remove all bindings to click event for all elements. Maybe a suggestion to turn off plugins or check you're not unbinding click for a parent element yourself.
The code you have posted is correct, so I suspect there's something else going on that you haven't considered.
Firstly, if there was an error somewhere (even not in that exact bit of code) that might cause it to stop working. Put an alert just after this line to check that it runs.
Check that no other elements are catching the event and stopping it from propagating. This has bitten me before in the past... If there's anything else handling a click which has stopPropagation() or return false in it, that might be the problem.
One thing I've found (though only with links going elsewhere) is that adding return false; in may help, if it's just firing the anchor off instead of evaluating the alert. I can't really say why this would be the case, but that's a solution I found to a similar problem recently.

Categories

Resources