0

This is likely a pretty basic question, but I'm having trouble coming up with an if/else statement for my nav-bar. I have a combination of external page links and specific IDs I want to scroll to on click in my navbar. Below is a snippet of the code I'm dealing with where I am unable to access external links because of the e.preventDefault. Basically I want to prevent default where internal linkID (and instead scroll down to that ID), and execute normally when menu option is an external link. Could I please get some help?

// if not an external link, scroll to specific ID when click on menu item
$('.webby-top-menu .navbar-nav a').click(function (e) {
    e.preventDefault();
    var linkId = $(this).attr('href');
    scrollTo(linkId);

    if ($('.navbar-toggle').is(":visible") == true) {
        $('.navbar-collapse').collapse('toggle');
    }

    $(this).blur();
    return false;
});

// stick navbar on top
$('.webby-top-menu ').stickUp();

Thank you!

Siguza
  • 21,155
  • 6
  • 52
  • 89
cbenny
  • 1
  • 1
  • 1
    Why not give links to external pages and links to specific IDs a different class name that you can use to add different event listeners for them? Then only have the e.preventDefault() in the event handler for links that don't point to external pages? – ray9209 Nov 10 '14 at 20:49
  • 1
    I don't see in that code where you're trying to do what you describe. Have you made an effort? – isherwood Nov 10 '14 at 20:49
  • possible duplicate of [Test if links are external with jQuery / javascript?](http://stackoverflow.com/questions/2910946/test-if-links-are-external-with-jquery-javascript) (one of many possible.) – Evan Davis Nov 10 '14 at 20:52
  • filtering external/internal links seems to be the general issue for OP. – Evan Davis Nov 10 '14 at 20:53
  • @Mathletics, I don't see a relevant solution on that question. Did you? It's not a question of internal vs. external, but anchor vs. hyperlink. – isherwood Nov 10 '14 at 20:54
  • @isherwood I think those questions give OP all the tools they need to solve this variant of the problem. External/internal, slash vs hash; both are about testing the `href` against some criteria. – Evan Davis Nov 10 '14 at 22:22

1 Answers1

1

Seems like checking for a hash symbol at the first character of your link's href attribute would do:

$('.webby-top-menu .navbar-nav a').click(function (e) {
    var link = $(this).attr('href').charAt(0);

    if (link === '#') {
        e.preventDefault();
        alert('Anchor!');
    }
});

Fiddle

isherwood
  • 58,414
  • 16
  • 114
  • 157