Marius Miliunas
Marius Miliunas

Reputation: 1063

Check whether jQuery method exists

I'm trying to check whether the jQuery has a .hashchange method reference to the window object like

$(window).data('events').hasOwnProperty('hashchange') ?
    $(window).hashchange(hashChange) :
    window.onhashchange = hashChange;

but i keep getting a "Uncaught TypeError: Cannot call method 'hasOwnProperty' of undefined" in both browsers that support & don't support the function. any ideas?

Upvotes: 1

Views: 1830

Answers (2)

JaredPar
JaredPar

Reputation: 754715

One way is to see if the property is simply undefined

if ($(window).hashchange === undefined) {
  // Not defined
}

Note: This actually checks whether or not the value is defined vs the name. It is possible to define the value with an explicit undefined value but the two are probably equivalent for your scenario

var x = {}
x.test = undefined;
x.hasOwnProperty("test") // true
x.test === undefined // true

Upvotes: 4

Naftali
Naftali

Reputation: 146300

$(window).data('events') === undefined

Therefor it has no properties.


What you need to do is 1st make sure that the data contains an object:

var window_data = $(window).data('events');

if(window_data !== undefined){
   window_data.hasOwnProperty('hashchange') ?
    $(window).hashchange(hashChange) :
    window.onhashchange = hashChange;
}
else {
    window.onhashchange = hashChange;
}

Upvotes: 0

Related Questions