Ways to engage students during scrolling using javascript

Having some trouble with my javascript, specifically with the navigation links. The code is supposed to apply an active class to the nav links when on that section of the page, but it's glitchy and flickers while scrolling instead of remaining active. Check out this JSFiddle for reference here. If you scroll slowly, you'll notice the "home" link briefly becomes active. I want each link to remain active after being clicked and throughout that entire section of the page.

I also have a sticky nav bar and smooth scrolling enabled with javascript, so I suspect there might be some conflict there. Any help would be greatly appreciated.

Here is the snippet of Javascript attempting to assign the active class:

var sections = $('section')
 , nav = $('nav')
 , nav_height = nav.outerHeight();

$(window).on('scroll', function () {
 var cur_pos = $(this).scrollTop();

  sections.each(function() {
    var top = $(this).offset().top - nav_height,
    bottom = top + $(this).outerHeight();

  if (cur_pos >= top && cur_pos <= bottom) {
   nav.find('a').removeClass('active');
   sections.removeClass('active');

  $(this).addClass('active');
   nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
     }
   });
 });

nav.find('a').on('click', function () {
 var $el = $(this)
 , id = $el.attr('href');

$('html, body').animate({
  scrollTop: $(id).offset().top - nav_height
   }, 500);

  return false;
 }); 

Answer №1

Is this what you were looking for? Although I didn't personally observe any flickering on my end, I noticed that the class was consistently being removed and added as I scrolled.

Here is a link to the updated code on JSFiddle

In order to address the issue, I made some key modifications by assigning a class to each section. Even though there are multiple sections in your code, assigning a class to them makes it simpler to manage. See example below:

<section id="home" class="section">

I utilized var sections = $('.section') to target all elements with the 'section' class.

The Javascript snippet has been revised to include checking for the active class:

if (cur_pos >= top && cur_pos <= bottom) {
  if(!$(this).hasClass("active")) {
    nav.find('a').removeClass('active');
    sections.removeClass('active');

    $(this).addClass('active');
    nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
  }
}

An additional tip is to store $(this) in a variable within the section loop like so:

var $this = $(this);

Afterwards, you can simply use $this throughout the loop for efficiency.

For more information on the hasClass method, refer to the following documentation: jQuery official documentation

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Clicking on a column or x-axis category in Highcharts will automatically include the job number in the page URL

Check out the code I've put together: http://jsfiddle.net/a9QwS/ I'm looking to add functionality where clicking on a column or x-axis label will append its data to the URL. For example, in PHP, I can do something like this: echo " <td sty ...

Creating a layout with multiple child elements using flexbox

I'm wondering if it's possible to achieve something like this: using flex-boxes with only three divs inside the wrapper. I know it would be simpler to create two columns, with one wrapping the larger div and another wrapping the other two blocks ...

What is the best method for integrating jQuery FullCalendar using AJAX?

I need assistance loading a full calendar using Ajax. The data will be passed from the controller in JSON format, but I am unsure of how to implement it. Can someone please help me with this? Here is my controller code: public function calenderHoliday(){ ...

Utilizing jQuery to Capture Select Change Events

I am trying to automatically select a hidden option based on the value selected in a visible select. Here is my jQuery code: $(document).ready(function() { var selected_val = $('#id_foo option:selected').val(); $('#id_bar').va ...

The functionality of autocomplete with $.post is not functioning as intended

Utilizing the autocomplete functionality provided by this plugin from commadelimited, I have developed a PHP script to retrieve data from my MySQL database. Here is the PHP script: <?php $connection = mysql_connect("my_host", "usr", "pwd"); // Establis ...

Trumbowyg plugin fails to display button panel on the interface

I've implemented a JavaScript plugin called Trumbowyg to create an HTML Editor (WYSIWYG). Despite no errors occurring during the instantiation and creation of elements with this plugin, I am facing an issue where the panel displaying buttons/options f ...

Surge the PrimeNG DialogModule by integrating the CalendarModule to enhance its functionality

Looking for a way to create an Edit popup dialog that includes an input form in Angular2 using the PrimeNG widgets. I have encountered issues with the dynamic content of the dialog box as shown in the screenshot. https://i.sstatic.net/r3INA.png I attempt ...

Is memory space consumed by the reduce accumulator?

I'm considering two different approaches and I'm unsure which one is recommended in terms of readability and memory allocation. From my understanding, both have the same space complexity as they both use some form of storage (two variables in the ...

Incorporating stick-to-top scroll functionality using AngularJS and ng

I am trying to implement a 'sticky' scroll on dynamic content. My current working example can be found here. It seems to be working, but I encounter a small 'flicker' when new items are appended. This issue seems to be related to the se ...

design and construct a three-dimensional shelving unit

After much searching and failed attempts, I am determined to create a stationary cube-shaped bookcase using CSS. Can anyone offer some guidance on how I can achieve this? I have included an image of the design I want to replicate. Thank you .scene { ...

Using Ajax to set the file target dynamically

Let me start by saying that I prefer not to use JQuery for any suggestions. I'm not a fan of how JQuery has become the de facto standard within JavaScript. Now, onto my issue: I want to pass a variable to a function that will then use that variabl ...

Tips for eliminating excess padding hidden by carousel controls

Below is the code snippet I have implemented: index.html html, body { margin: 0; padding: 0; } body { width: 100%; height: 100%; } .container { width: 100vw; height: 100vh; background-color: #fc2; } /*.container .carousel slide .carou ...

What is the process for implementing a Node.js emit event on the server side to notify when new records have been inserted into the database

I am currently working on developing a Node.js socket backend that is required to send out new records to the client. What I mean by this is, picture having a MySQL database and Node.js running - I aim to send out in real-time any newly inserted record fr ...

Tips for manipulating the appearance of a parent element using CSS and VueJS

I'm currently working on a project where I need to loop through a set of users in order to create a table using the VueJS 'for' statement. One specific column is named "approved". If the value in this column is true, I want the entire row i ...

The loading bar function seems to be malfunctioning when paired with the navbar element <nav> in an HTML document

Can you assist me with a coding issue I am facing? I have implemented a loadingbar on my webpage similar to YouTube, and it works perfectly on the page itself. However, when I try to integrate it with a navigation bar, it stops working. Below is the code ...

Investigating High Energy Usage on Vue.js Websites: Identifying the Root Causes

My Vue.js application has grown to be quite large with over 80 .vue components. Users have been complaining about their phone batteries draining quickly and Safari displaying a "This webpage is using significant energy..." warning. I have tried investigat ...

Using Django to rewrite URLs and transferring a parameter through JavaScript

Following up on my previous question, I am facing a challenge in passing a parameter to a view that is only known after the JS executes. In my URLConf: url(r'^person/device/program/oneday/(?P<meter_id>\d+)/(?P<day_of_the_week>\ ...

Ignoring custom elements does not occur when the child is set to display as inline-block

My code includes custom elements that exhibit strange behavior when a child element has the "display: inline-block" style. Let's examine these two div elements: <div style="padding: 4px;"> <randomcustomelement style="background-color: y ...

Tips for: Minus a CSS property from a JavaScript variable height?

Is there a way to deduct the navbar_height by 2rem in the code snippet below? navbar_height = document.querySelector(".navbar").offsetHeight; document.body.style.paddingTop = (navbar_height - 2 ) + "px"; Appreciate your help! ...

Utilize Google API V3 to create a dropdown selection list of locations, extracting latitude and longitude values from a JSON text file

I am working on creating a map using Google Maps API v3. I have implemented a dropdown select list for different places and I am pulling the latitude and longitude values from it. Initially, I manually added the options like this: <option value= ...