Vlad Vlad - 5 months ago 9
Javascript Question

Remove class when scrolled to the href atribute

Currently I remove class from the element in 2000

setTimeout(function(){
$('.nav-item a').removeClass('active');
}, 2000);


How can I amend my code to remove class when the 'autoscroll' is finished?

$('.nav-item a, .nav-brand a, .button, .footer2 a').click(function() {
event.preventDefault(); // default action of the event will not be triggered, eg will not change links name
var windowSize = $(window).width();
if (windowSize >= 769) {
$('html, body').animate({
scrollTop: $($(this).attr('href')).offset().top - 51
}, 1500);
}
else if (windowSize <= 768) {
$('html, body').animate({
scrollTop: $($(this).attr('href')).offset().top - 102
}, 1500);
}
return false; });


I guess I should somehow use
attribute href
, but I am not sure how.

Answer

You can do it by defining a complete callback into animate method.

$('.nav-item a, .nav-brand a, .button, .footer2 a').click(function() {
  event.preventDefault(); // default action of the event will not be triggered, eg will not change links name
  var windowSize = $(window).width();
  var scrollY;

  if (windowSize >= 769) {
    scrollY = $($(this).attr('href')).offset().top - 51;
  } else {
    scrollY = $($(this).attr('href')).offset().top - 102;
  }

  $('html, body').animate({
    scrollTop: scrollY
  }, 1500, function() {
    $('.nav-item a').removeClass('active');
  });

  return false;
});
Comments