I store a jquery object (a collection of html elements) but when I come to reference the object in another function it comes back as ‘undefined’! Here’s my code:
this.container = $('#slide-menu'), // The menu container (e.g. a UL)
this.items = this.container.find('.menu-item'); // The menu items (e.g. all li's)
this.links = this.items.find('.link'); // The menu links
this.getCurrent(); // Set the current menu-item
this.getPrev(); // Set the previous menu-item
this.getNext(); // Set the next menu-item
console.log(this.items); // !!! The items exist here !!!
// Setup the menu items click events:
this.items.bind('click', function(e) {
console.log(this.items); // !!! But not here !!! ???
e.preventDefault();
o = $(e.currentTarget); // Set jquery object
if (!o.hasClass('active')) { // Prevent action on current menu-item
this.items.find('.active').removeClass('active'); // Remove the current active menu-item
o.addClass('active'); // Set new active menu item
Does anyone have any idea why this is happening because it’s driving me crazy and as far as I can see this should not be possible. Is javascript is broken?! Hmmm, what do you think?
Never.
Or when it’s not where you think it is.
No, Javascript is not “broken”.
You’ve assumed
this.itemsalways refers to the same thing. It does not. Inside yourbind,thisis the thing that was clicked on, rather than whatever it is outside of that callback function.Inside your callback, you ought to write
$('#slide-menu').find('menu-item')rather thanthis.items.