Taylor Osborn Taylor Osborn - 4 months ago 15
Ajax Question

Have existing JavaScript that smooth scrolls to id's, would like help adding an exception for a specific id

The JavaScript here will smooth scroll to all hash links. I need the

id=nav
and its resulting hash link,
/#nav
to be ignored by the below JavaScript.
id=nav
is used in the menu responsiveness and when it is commandeered by the below JavaScript it breaks the menu.

Can someone please advise how I can ignore a specific id in the below JavaScript?

Also I made a working HTML demo you can seen below.



.top {
position: fixed;
top: 0;
}
a {
margin-left: 20px;
display: block;
}
#nav {
height: 800px;
background-color: #777;
display: block;
}
#test1 {
height: 800px;
background-color: #ccc;
display: block;
}
#test2 {
height: 800px;
background-color: #111;
display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top - 80
}, 500);
return false;
}
}
});
});
</script>

<body>
<div class="top">
<a href="#nav">nav</a>

<a href="#test1">1</a>

<a href="#test2">2</a>
</div>

<div id="nav"></div>

<div id="test1"></div>

<div id="test2"></div>
</body>




Answer

Add this line right after the 2nd line of JavaScript:

if($(this).attr("href") == "#nav") return;

So it looks like this:

$(function() {
    $('a[href*="#"]:not([href="#"])').click(function() {
        if($(this).attr("href") == "#nav") return;
        //... Rest of code

JSFiddle

How this works is it checks that the href attribute's value of the clicked link isn't "#nav". If it is, the function returns false and isn't executed.

Comments