Your code looks as though you're using jQuery. If you're handling an event that was bound using a jQ function, like on
, delegate
or bind
, jQ will wrap the event object for you. You should have access to jQ's preventDefault()
, stopPropagation()
and stopImmediatePropagation()
methods, rendering your ternary irrelevant.
If you're binding the event yourself, make sure the event
variable isn't undefined:
elem.onclick = function(e)
{//e should contain the event object, except for IE<9
e = e || window.event;//old IE's set the event as a property on the global object
};
If you find this a ropey, and who can blame you, you could augment the Event.prototype
. I do this for code that needs to support old versions of IE, and it hasn't let me down yet...
The ternary operator can't be sure how to evaluate the statement event.preventDefault ? event.preventDefault() : event.returnValue = false
. You might mean for the JS engine to interpret the code as (event.preventDefault ? event.preventDefault() : event.returnValue) = false
(assign false
to the result of the ternary) or (event.preventDefault ? event.preventDefault() : event.returnValue = false)
(treat the entire statement as a ternary expression).
To avoid this ambiguity, group the assignment expression, to let JS know that the assignment is the or
part of the ternary:
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
Having said that, using a ternary as a statement is generally considered to be bad practice. a far more common way of writing your code is:
e.returnValue = false;//returnValue is set on Chrome and, I believe FF, anyway
//if some browser Event objects don't have this, there's no harm in adding a property
//if the event object is read-only, the assignment will fail, silently
if (e.preventDefault)
{
e.preventDefault();
}