Skip to content
Advertisement

How to stop JS scroll to top function overriding links in nav bar

Hi I have a navbar as follows:

<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top back-to-top">
    <div class="container-fluid">
        <a href="https://www.google.com"><img class="logo" alt="logo" src="assets/Logos/ntc_white_basic.svg"></a>
        <a class="navbar-brand" href="index.html">Test Navbar</a>
    </div>
</nav>

With a JavaScript function to return to the top of the page when the navbar is clicked as follows:

  $('.back-to-top').click(function () {
    $('html, body').animate({ scrollTop: 0 }, 'slow');
    return false;
  });

However, I still want to be able to follow the links within the navbar but they are being overridden by the JS function so when you click on them now it scrolls to the top.

How do I make it so the links within the navbar are still useable but the ‘back-to-top’ function works when you click on the rest of the navbar, thanks.

Advertisement

Answer

You can add an exception to the a tag by registering a second click event with the return of return false:

...
}).on('click', 'a', function(){
    return false;
});

And write a second click event for tag a only:

$('a').click(function () {
    console.log('click a');
});

I wrote a console.log() so that you would see what event is triggered by the current click.

$('.back-to-top').click(function () {
    console.log('click only back-to-top');
    $('html, body').animate({ scrollTop: 0 }, 'slow');
    /*return false;*/
}).on('click', 'a', function(){
    return false;
});

$('a').click(function () {
    console.log('click a');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top back-to-top">
    <div class="container-fluid">
        <a href="https://www.google.com"><img class="logo" alt="logo" src="assets/Logos/ntc_white_basic.svg"></a>
        <a class="navbar-brand" href="index.html">Test Navbar</a>
    </div>
</nav>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement