views:

233

answers:

5

It seems like I type "function(){return false;}" some what too frequently too prevent actions from happening... is there a short cut?

A: 

You can cancel an event default action by using the preventDefault method:

$("form").bind("submit", function(event){ 
  event.preventDefault(); 
});
CMS
A: 

Do you really think that's too much typing?

Why not have a global variable named f set to false, and use function() {return f;}

zildjohn01
function f() { return false; }
Ates Goral
Seems like a false economy :-7
Chris Noe
@Ates -- got me there :)
zildjohn01
+5  A: 

You could declare a named function like this:

function always_false() { return false; }

then use "always_false" wherever you would have created the anonymous function previously.

Greg Hewgill
I'm thinking call it something shorter like ff() (bad name I know) and so that it's even shorter but this seems like the right idea.
Unkwntech
What, this will not work, -1, please explain.
Luca Matteis
Oh, "always_false" would be the actual listener?
Luca Matteis
then I would expand that, since he's using jquery to: function always_false(e){e.preventDefault();}
Luca Matteis
+2  A: 

I often have a "no op" function defined at the top of my common js file:

function nop() { return false }

I use it whenever I need a "do nothing" or a "cancel event" handler (eg div.oncontextmenu = nop). In IE this has the added benefit that memory does not leak when creating similar [anonymous] functions on the fly and assigning them to event handlers. At least that's what IE Drip tells me.

Crescent Fresh
return false; doesn't "cancel event"s.
Luca Matteis
@Luca: try it some time.
Crescent Fresh
A: 

Just set the event handler to null. This is cleaner than assigning to a "return false" function IMO because it removes the event handler altogether.

myButton.onclick = null;

mahemoff