add another class to a scrolling js

62 views Asked by At

I'm very new to javascript and have no clue on how to add this myself.

    $(document).ready(function() {
  $('.nav a').on('click', function(e) {
    e.preventDefault();

    var target = $(this).attr('href'),
      offset = $(target).offset().top - 70;

    $('html, body').stop().animate({
      scrollTop: offset
    }, 500);
  });
$('.scroll ul li').click(function(e) {
  var $this = $(this);
  var prev = $(this).parent().find('.active');
  prev.removeClass('active');
  if (!$this.hasClass('active')) {
    $this.addClass('active');
  }
  e.preventDefault();
});
});

that's the scrolling code I'm using and it works great for my navbar!

but I just added this button

  <a href="#about" class="btn btn-circle page-scroll">
    <i class="fa fa-angle-double-down animated"></i>

how do I make it so that the script also works with that button in the same way? http://codepen.io/sbxn14/pen/egmKRr <-- my codepen that contains this site.

I hope someone can help me.

EDIT:
While I'm adding it. is it possible to make it so that the active link on the navbar switches if I manually scroll through the page? I've been looking on google on this but haven't been able to find anything.

1

There are 1 answers

2
Obsidian Age On

To get your button to scroll like the links in your navbar, all you have to do is add the new class to the click handler.

Instead of:

$('.nav a').on('click', function(e) {

You simply add the new class to the click handler as such:

$('.nav a, .page-scroll').on('click', function(e) {

Alternatively, you could do it like:

$('.nav a').add('.page-scroll').on('click', function(e) {

You can also get the navbar to highlight the newly-visible area by adding the .active class to the corresponding navbar segment when the button is clicked, as follows:

$('.page-scroll').click(function(e) {
   $('.navbar-nav li:nth-child(2)').addClass('active');
});

Here's an updated pen showcasing both the button scrolling to the About section, and changing the highlighted part of the navbar.

Hope this helps! :)