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

Is there no "on" function available in the Node readline module?

I am currently working on building a Node.js application that reads a text file line by line using the 'readline' module and displays it in the console. var lineReader = require('readline'); lineReader.createInterface({ input: fs.cre ...

Error encountered in jQuery validation: Uncaught TypeError - $(...) ""valid is not a function" is displayed with proper references and order

When I try to call a function, I keep getting an error message that says "Uncaught TypeError: $(...).valid is not a function"... JS $('input[data-val=true]').on('blur', function() { $(this).valid(); }); HTML <div class="col-x ...

Send an array using jQuery's $.post method

I am experiencing an issue with sending an array in $.post to PHP. When I use var_dump, the result is showing as "NULL" and JSON.stringify is not working. JQUERY var photobox = []; photobox.push(e.target.result); $.post("../modules/upload.php",{"imag ...

How can I implement conditional rendering with React on a div element?

Is it possible to implement conditional rendering by simply adding the boolean checked isVisible=true onto the div? Will this ensure that it only renders when true? Could there be any potential issues with the component's state changing after renderi ...

ngModel.$setValidity is a one-time operation

Currently, I am working on a validation issue with an angular bootstrap ui datepicker popup. I have set the max and min dates for validation, which work when the user selects a date from the calendar. However, if the user manually inputs a date, these vali ...

Is it possible to change the text of a scrollspy dropdown to a default text when it is not actively tracking any items?

I am new to Vue and currently implementing Bootstrap Vue Scrollspy (view example here). My sticky dropdown is tracking all referenced content and updates with the current section in view. You can check out my code sample here. Is there a way to set the d ...

Transmitting a jQuery array from the client to the server using AJAX in

I've looked at so many posts about this issue, but I still can't get my code to work. My goal is to retrieve a PHP array of values from the checkboxes that are checked. Here is my code snippet: <!doctype html> <html> <head> & ...

I'm having trouble finding the issue in this straightforward code snippet. Can someone pinpoint the error for

(server-side) const express = require('express'); //setting up app instance const app = express(); //middleware const bodyParser = require('body-parser'); app.use(express.urlencoded({extended: false})); app.use(express.json()); //imple ...

The CSS file is not connecting properly despite being located within the same directory

I have double-checked that both of these files have the correct names and are in the exact same directory. However, for some mysterious reason, the CSS is not applying any styling to my page. I would greatly appreciate any assistance with this issue! Belo ...

Is React.js susceptible to XSS attacks through href attributes?

When user-generated links in an href tag appear as: javascript:(() => {alert('MALICIOUS CODE running on your browser')})(); This code was injected via an input field on a page that neglects to verify if URLs begin with http / https. Subseque ...

Activate a dropdown menu following the selection of a date on a calendar input using vue.js

What I need to do is have two select fields, one for 'days' and the other for 'hours'. When a day is selected, the user should then be able to choose between two available time slots. If they choose day two, the available time slots sh ...

The Vue.js application is failing to toggle the integrated code

I am new to using Vue and I am trying to create a vertical navigation bar. When the menu icon is clicked, the navbar should toggle. Here is my menu icon code: <button type="button" id="sidebarCollapse" class="btn btn-info [collapsed?'': ...

Apply CSS styles to the checkbox

I am new to CSS and I need help styling a checkbox element. When the user selects one of the checkboxes, I want the background color to change to yellow. Thank you for any assistance you can provide! .radio_toggle { float:left; } .radio_toggle label ...

Run the GetServerSideProps function every time the button is clicked

Struggling with my NextJS app development, I encountered an issue while trying to fetch new content from an API upon clicking a button. The server call is successful, but the update only happens when I refresh the page rather than triggering it with the bu ...

Error encountered: Unspecified "from" address in the provided or default options

Seeking guidance on a project related to Ethereum and Solidity, part of Udemy's course titled "Ethereum and Solidity: The Complete Developers Guide." I am currently working on building the front-end for a Kickstarter alternative. I am facing an issue ...

Event callback method in jQuery

Currently working on a captcha system that incorporates jQuery to refresh the image in case it's not readable. $('a#reload').click(function(){ $(this).removeClass('reload').addClass('reloading'); var ts = Math. ...

My goal is to retrieve the top three highest rated products

// @route GET /api/products/top // @desc Retrieve top-rated products // @access Available to the public router.get( '/best', asyncHandler(async (req, res) => { const bestProducts = await Product.find({}).sort({ rating: -1 }).limi ...

Utilizing Font Awesome for social icons in a Vue component display

Currently, I'm in the process of building my own website and making the switch from traditional HTML, CSS, and JS to using VueJs. I've hit a roadblock when trying to transfer some code from my original HTML file to a Vue JS component, specificall ...

Storing Form Input in Browser's Local Memory

I am currently working on a form section where individuals can input their email addresses. However, I have encountered a couple of issues: (1) After submitting an email address, the page refreshes. While I understand that this is inevitable without usin ...

Show or conceal advertisement based on user role

I have developed a custom Web Control that acts as a container for a mobile banner, but I want to hide it from users who are admins. So far, I've attempted the following: <mob:MobileBanner runat="server" ID="MobileBanner" Visible='<%# Not ...