navigation menu 'selective emphasis' feature

I have created a JQuery script that will highlight the 'About', 'My Projects', or 'Contact Me' text on the navigation bar when the corresponding section of the page is in view. To achieve this, I am using a scroll() event listener:

$(document).scroll(function myFuction() {
    if ($(document).scrollTop() >= $("#contactMe").offset().top) {
        $("#contactButton").addClass("active");
        $("#projectButton").removeClass("active");
        $("#aboutButton").removeClass("active");       
    } else if ( $(document).scrollTop() > $("#portfolio").offset().top && $(document).scrollTop() < $("#contactMe").offset().top) {
        $("#contactButton").removeClass("active");
        $("#projectButton").addClass("active");
        $("#aboutButton").removeClass("active");
    } else if ( $(document).scrollTop() > $("#about").offset().top && $(document).scrollTop() < $("#portfolio").offset().top)  {
        $("#contactButton").removeClass("active");
        $("#projectButton").removeClass("active");
        $("#aboutButton").addClass("active");
    }
});

As the user scrolls, the function determines the position of the top of the page using scrollTop(), and then applies or removes the "active" class to highlight the appropriate text.

I am aware that performing actions within an event listener may not be the best approach, but I haven't found an alternative method yet. Perhaps I am trying to reinvent the wheel here?

I had hoped that the Bootstrap library would provide a predefined class for this functionality, but I have been unable to locate one so far.

Answer №1

To optimize your code, consider assigning a class to all items, caching them as a jQuery collection, and then checking if they are within the viewport during scroll events in order to trigger specific actions.

Here's a quick demo:

var $items = $('.item')
var $window = $(window);
var $document = $(document);

function inViewport(el) {
  var rect = el.getBoundingClientRect();
  return (
    rect.bottom > 0 &&
    rect.right > 0 &&
    rect.left < $window.width() &&
    rect.top < $window.height()
  );
};

$document.on('scroll', function(){
  $items.each(function(){
    if(inViewport(this)) {
      $items.removeClass('active');
      $(this).addClass('active');
      return false;
    }
  })
}).trigger('scroll');
.item {
  width: 100%;
  height: 150px;
  margin-bottom: 50px;
  background-color: #ddd;
}

.item.active {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item"><span>#1</span></div>
<div class="item"><span>#2</span></div>
<div class="item"><span>#3</span></div>
<div class="item"><span>#4</span></div>
<div class="item"><span>#5</span></div>
<div class="item"><span>#6</span></div>
<div class="item"><span>#7</span></div>
<div class="item"><span>#8</span></div>
<div class="item"><span>#9</span></div>
<div class="item"><span>#10</span></div>

To enhance performance, it is recommended to throttle scroll calls either by using https://lodash.com/docs/4.17.4#throttle or your custom implementation.

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

How is it possible for the output to be a string array when the variable was declared as a number in TypeScript?

Snippet: function sampleFunction(sample:string|number|string[]) { if(typeof sample == "string") { console.log("Sample is String " + sample); } else if(typeof sample == "number") { console.log("Sample is Number " + sampl ...

AngularJS enables you to easily manipulate image width and height using the ng-file-upload feature

Seeking assistance with validating image width and height based on a 1:3 ratio prior to uploading using ng-file-upload. The validation should occur before sending the image to the server. Unsure how to retrieve the dimensions of the selected image for val ...

What is the best way to track and display the window.scrollY value in the console using Next.js

Unfortunately, my ScrollToTop component is not functioning correctly within my app. I have exhausted all possible debugging methods but am still unable to determine why the scrollY value is not being logged as expected. Even after moving the snippet to a ...

Content formatted with a gap

I wish to include a gap between each sample usage with markdown. For instance: .kick Sarah, .kick John, .kick Mary .setDescription(`**Usage :** \`${settings.prefix}${command.help.name} ${command.help.usage}\`\n**Example :** \`${setting ...

Exploring ways to retrieve boolean values with Angular and PHP

I am currently learning Angular and PHP and I am trying to make some modifications to the tutorial found at . Specifically, I want to change the second value to a checkbox and retrieve its value using both Angular and PHP. However, I am encountering an iss ...

When you click on Highcharts, a bigger graph will be displayed

I am working on a feature that allows users to zoom in on small charts on my website. This involves revealing an overlay div and displaying a larger chart with the same data as the clicked chart inside it. function DrawSmallChart() { chart_data = [1, 2, 3 ...

Error message: After using gulp-npm-dist to copy only the dependency modules, the node module was not

I'm currently exploring different methods to package only the necessary node_modules dependencies for my project. After some research, I came across gulp-npm-dist and created a gulpfile.js. var gulp = require('gulp'); var npmDist = requir ...

To extract three records from storage and store them in the dbResult using a promise join technique

How can I efficiently retrieve and store 3 records in dbResult using promise join? Currently, I have code that retrieves a single record as shown below: req.oracleMobile.storage.getById(registry.getIncidentPhotoStorageName(), incident_id + '_01&apos ...

Troubleshooting bitrate and quality issues in AWS MediaConvert

Whenever I attempt to initiate a MediaConvert job in CBR, VBR, or QVBR mode with Bitrate or MaxBitrate exceeding 250,000, an error occurs. The message reads: "Unable to write to output file [s3:///videos//***/original.mp4]: [Failed to write data: Access D ...

Angular code is malfunctioning and not delivering the expected results

I currently have setup the code below: var videoControllers = angular.module('videoControllers', []); videoControllers.videoControllers('VideoDetailController', function($scope, $routeParams, $http){ $http.get('http://localho ...

Utilizing the array result obtained from the fetch function

Seeking assistance with a coding issue. I am puzzled as to why I am unable to utilize the data returned from an API call outside of its function, even though there are no errors occurring. The fetchUser function successfully retrieves the data from the API ...

Seeking help with the conversion of jQuery code to Angular

A table on our website is dynamically populated using jQuery ajax. Here is the code snippet responsible for this functionality: $.ajax({ type: "POST", cache: false, url: "/files/event_lister.php", // script that fetches data from ...

Stop RequireJS from Storing Required Scripts in Cache

It seems that RequireJS has an internal caching mechanism for required JavaScript files. Whenever a change is made to one of the required files, renaming the file is necessary in order for the changes to take effect. The typical method of adding a version ...

Is it necessary to only override the monospaced font?

Can the monospace font in Angular Material be customized for just the <code>foo</code> blocks? I want to use a font where the number zero 0 looks distinct from the letter oh O. ...

What is the best way to input an argument into my Javascript code using the command line?

Whenever I run my JavaScript file called "login.js" from the command line using "node login.js", I find it necessary to manually edit the URL inside the file if I want to change it. It would be more convenient for me if I could pass the URL as a command l ...

Real estate listing featuring unique symbols

How do I include the ' character in properties when writing my object, like this: const championsList = { Kha'Zi: '...', }; Any suggestions on how to achieve this? ...

Adjust the image to stretch and crop appropriately to perfectly fit the specified dimensions

I have a div with an image inside of it, and the overflow of the div is set to hidden so that the image will be cropped if it exceeds the width or height. It was working correctly, but sometimes it doesn't. What could be causing this issue? Here is th ...

Guidance on creating a smooth fade-out effect for a div using jQuery when a text box is left blank

Currently, I am trying to send the contents of a textbox with the class "searcher" via an AJAX request triggered by the keyup event. My goal is to avoid sending the AJAX request if the textbox with the class "searcher" is empty and also clear the content o ...

Could it be that express-session is not compatible with express 4.13?

I have followed the setup instructions for express-session as outlined in the documentation, but it seems that my cookie is not being created. According to the documentation, simply setting the request.session value should automatically set the cookie. How ...

Why is it possible for the EXPRESS+EJS template to access CONFIG without explicitly passing it when rendering?

Currently exploring my knowledge of node.js alongside express and the ejs template. As I delved into some code, I stumbled upon the fact that they were able to invoke config in the template without explicitly passing it as a variable during rendering. You ...