RSS - Latest posts Posts Tagged ‘JavaScript’

Home » Tags » JavaScript
31Mar
2011

jQuery Multiple Events Without Default Behaviour

Sometimes you trip over the little things.

With several people working on the same page while we were recreating some JS functionality from scratch I’ve noticed one of my buttons suddenly stopped working. Scratched my head a bit, and for a minute thought that maybe it’s not having a “return false;” in my jQuery live() event handler.

Turned out though that it was actually one of the other developers actually putting a “return false;” in their event handler that just happened to target the same element…

Ideally we needed to propagate the event through a variable number of events but prevent the default behaviour of a link kicking in. preventDefault() to the rescue! :)

$('#tag').live('click', function(event){
    (...)
    event.preventDefault();
});

Now, before blindly applying this piece of code I’d encourage everyone to first read up on why “return false;” is evil. ;)

And for a quick reference here’s a table featured on a related StackOverflow question:

  stop propagation prevent default action prevent “same element” event handlers
return false X X  
preventDefault   X  
stopPropagation X    
stopImmediatePropagation X   X

Categories:

14Jun
2009

Hitch. Object-oriented event handlers with jQuery

Moving to jQuery from YUI has been a 99% positive experience. Probably the only thing I’ve really missed was the ability provided by YUI Event to control the object scope that an event handler was executed in.

(more…)

Categories:

7Nov
2008

Nested sortable using jTree – clickable links

jTree is a lightweight solution for nested, sortable lists based on jQuery. I’ve been trying to find a good solution for quite a while, however the only good competitor to jTree is now not compatible with the new jQuery (1.2.6). After getting fed up at work with including totally different sets of javascript files depending on whether the nested sortable was needed on a page or not I have decided it was time for some clean-up.

Minimal is a very good word to describe jTree, which most of the time is good, however sometimes you might just want a little bit more. One of the biggest issues for me was lack of clickable links inside the LIs. Fortunately after some tweaking I came up with a hacky but working solution:

if ($("#jTreeHelper").is(":not(:animated)") && e.button !=2) {
 	//	Allow for clickable links
	if(new String(e.target).match(/(f|ht)tp(s{0,1}):///ig)){
 		return false;
	}
	$("body").css("cursor","move");

Just add the highlighted lines in the jquery.jtree.js file. Basically it just checks if the target of the click is a link and if it is it ignores the dragging.

Categories: