0

Here is the scenario: I have 2 sets of navigation, main and secondary. The main navigation will always exist on a page and the secondary nav will not always be present. On the pages that DO contain the secondary nav, I want the main navigation to do something on mouseenter and mouseleave only when a class of "affix" has been attached to the secondary nav (after the page has been scrolled down to a certain point, but that is a separate piece of code).

The code I currently have is as follows:

var navItem = $('.main-navigation');
var stickyNav = $('.tabbed-sticky-nav.affix');

if (stickyNav == null || stickyNav == 'undefined') {
    doNothing();
    return;
} else {
    navItem.mouseenter(function() {
        console.log("Hover");
    });
    navItem.mouseleave(function() {
        console.log("Out");
    });
}

function doNothing() {
    console.log("Object not found");
}

When I run this as it is, the nav items always fire the code whether or not the subnav is on the page. I should probably be first checking if .tabbed-sticky-nav exists on the page, that way if the page doesn't have the secondary nav then don't bother checking for anything on hover. However, if the .tabbed-sticky-nav DOES exist and has the class of "affix" added to it, only then do I want the hover actions of the main nav to potentially apply. How can I change things so this cleanly checks and executes for these circumstances?

Denzy
  • 31
  • 8
  • 1
    sticky nav is probably not equal to `null` or `undefined`: https://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery – Max Baldwin Jul 31 '18 at 15:09
  • This isn't an answer to the question, but you generally should not compare with a string `"undefined"`, just use the keyword: `something === undefined`. – ggorlen Jul 31 '18 at 15:39

1 Answers1

2

jQuery always returns something, so the way to check if the elements exist is to use the length property. That will tell you how many elements were returned by the given selector.

if (!stickyNav.length){
    ...
}
sbrass
  • 905
  • 7
  • 12
  • Thank you, while there were a couple other issues this was the reason I was having difficulty debugging things. – Denzy Jul 31 '18 at 17:08