Best way to check JavaScript object's value if object may be undefined

javascript, jquery

Solution

You don't need comparisons to `undefined`. Just do a truthy test. Also the test for the `className` isn't needed. The `===` comparison will cover it.

 if (
    event.originalEvent &&
    event.originalEvent.currentTarget &&
    event.originalEvent.currentTarget.activeElement &&
    event.originalEvent.currentTarget.activeElement.className === 'dontClick'
  ) {

but then you're doing more work than needed anyway since jQuery gives you a reliable `currentTarget`.

 if (
    event.currentTarget.activeElement &&
    event.currentTarget.activeElement.className === 'dontClick'
  ) {

or if you're in a handler, just use `this`.

 if (this.activeElement && this.activeElement.className === 'dontClick') {

Problem

I have a `textarea` that I have a blur event attached to. I don't want the blur event to run if the user clicks on a specific `span.dontClick` on the page. However if the user clicks on anything other than the `span.dontClick` I do want the blur event to run. I have found a way to do this, but it looks awful, feels very hackey, and I'm guessing there is a better solution out there. Here's what I've come up with: ``` if (event.type === 'focusout') { if ( typeof event.originalEvent !== 'undefined' && typeof event.originalEvent.currentTarget !== 'undefined' && typeof event.originalEvent.currentTarget.activeElement !== 'undefined' && typeof event.originalEvent.currentTarget.activeElement.className !== 'undefined' && event.originalEvent.currentTarget.activeElement.className === 'dontClick' ) { // abort the code for the blur event (in effect, do nothing) } else { // run code for when a user blurs by not clicking on span } ``` It should probably be noted that the `event` object is from a jQuery event handler. I'm not sure if it is different or the same as the native `event` objects. It should also be noted that this fails silently for most browsers but I get a debug window in IE if I don't specify the 'undefined' state for each object all the way down the line... If anyone has a more elegant solution I would really appreciate seeing it. Thanks!

Original source