Alter the Header/Navigation to switch colors depending on the section of the website currently being viewed

I'm currently revamping my personal portfolio website and had an idea for a cool feature. I want the header/navigation bar to change color based on which section of the webpage it's in (the site is one page only).

My initial thought was to add onclick events to the links that lead to different sections of the page. However, this method wouldn't allow me to update the color of the header when a user scrolls manually to a new section.

If anyone could guide me in the right direction, I would greatly appreciate it as I'm unsure where to begin.

For those interested, here is the current version of the website:

www.kylebinger.com

Below is the HTML markup related to the header:

<header>
    <div class="container">
        <nav>
            <a href="#home">Welcome</a>
            <a href="#featuredWork">Work</a>
            <a href="#caseStudy">Case Study</a>
            <a href="#about">About</a>
            <a href="#contact">Contact</a>
        </nav>
    </div>
</header>

Thank you in advance for any assistance.

Answer №1

To achieve the desired effect, you can utilize JQuery's offset and scrollTop functions. The .offset() function retrieves the current coordinates of an element, while .scrollTop() function returns the current scrollbar position. By comparing these values and applying CSS changes when certain conditions are met, you can dynamically alter the appearance of elements on your page. Here is a sample code snippet demonstrating this concept:

var top1 = $('#home').offset().top;
var top2 = $('#featuredWork').offset().top;
var top3 = $('#caseStudy').offset().top;

$(document).scroll(function() {
  var scrollPos = $(document).scrollTop();
  if (scrollPos >= top1 && scrollPos < top2) {
    $('#change').css('background-color', '#f00');
  } else if (scrollPos >= top2 && scrollPos < top3) {
    $('#change').css('background-color', '#0f0');
  } else if (scrollPos >= top3) {
    $('#change').css('background-color', '#00f');
  }
});
body {
  margin: 0;
  padding-top: 30px
}
header {
  position: fixed;
  top: 0;
  width: 100%;
  height: 30px;
  background-color: #000;
}
section {
  height: 500px;
  background-color: #aaa;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header id="change">
  <div class="container">
    <nav>
      <a href="#home">Welcome</a>
      <a href="#featuredWork">Work</a>
      <a href="#caseStudy">Case Study</a>
    </nav>
  </div>
</header>

<section id="home">Content</section>
<section id="featuredWork">Content</section>
<section id="caseStudy">Content</section>

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

"Unable to get elements by tag name using the getElementsByTagName method in

function updateLayout() { var para = document.getElementsByTagName("p"); para[0].style.fontSize = 25; para[1].style.color = "red"; } <p>Text in paragraph 1</p> <p>Text in paragraph 2</p> <p>Text in paragraph 3</p& ...

Tips for concealing Vimeo URL on browser's inspect element

I've been attempting to conceal the Vimeo video URL from the browser, but it doesn't seem to be working correctly. I'm utilizing the Jplayer plugin to play a Vimeo video, and while it functions properly, the video links are still visible in ...

What could be causing my page div to continuously expand on ios devices only?

I'm facing a strange issue where the div element in my document keeps growing endlessly. This problem has been observed on iPhone with iOS 5.1 and 6. It's fascinating to watch the height and min-height values of the page increase continuously, ca ...

I'm having trouble understanding the distinction between this.query and this.query.find(). Can you explain the difference to me?

Currently, I am working on a MERN tutorial where I am developing a full E-commerce application. This is the class that handles querying and various other tasks. constructor(query, querystr) { this.query = query; this.querystr = querystr; con ...

Dealing with form errors - Using Node.js and Express Framework

Is there a way to handle errors that occur when dealing with null form inputs or unavailable cities from the weather api service? Sometimes, when an empty query or a misspelled city is inputted, the server returns errors and halts operation. app.get("/", ...

Can you identify any issues with this Basic authentication code for an HTTP-Get request?

My setup consists of node.js restify as the backend for running a REST API server, and angularjs as the front-end for making HTTP GET calls. The REST server is configured with HTTP Basic Authentication using the username foo and password bar. To confirm t ...

Find all paragraphs with the CSS property "background-color" using JQuery

My task involves modifying the CSS of a paragraph tag that has a background color of #aaddff. The code I have written seems to be missing something, as the border is not appearing as expected. Should I use element.style or is there a different approach I ...

Having trouble with Javascript not detecting when it's empty?

Recently, I have been attempting to modify the color of a submit button when a form is empty. As a beginner in this area, I am somewhat puzzled as to what mistake I might be making. I will share the current code with you in hopes of receiving some guidance ...

Tips for implementing ::before and ::after pseudo-elements within an anchor tag

Can you provide guidance on adding ::before pseudo-element inside an anchor tag? https://i.sstatic.net/tojNE.jpg ...

Is the NodeJS debugger prone to crashing when utilizing `this` to invoke an unidentified function?

My JavaScript file contains the code below: (function (context) { console.log(123); debugger; })(this); When I run my script in debug mode like this: $ node debug script.js I noticed that the other lines in debug mode are not colored green. Wha ...

The vertical scrolling functionality of the MUI DataGrid in Safari may occasionally fail to work

Utilizing the <Box> component from MUI core and the <DataGrid> component from MUIX, along with some other components, I have created a data grid that has the following appearance: https://i.sstatic.net/Gc8sP.png When the number of rows exceed ...

Obtaining Input Field Value in Angular Using Code

How can I pass input values to a function in order to trigger an alert? Check out the HTML code below: <div class="container p-5 "> <input #titleInput *ngIf="isClicked" type="text" class="col-4"><br& ...

Tips for eliminating repeated values in a textbox

<script> $("#filter").on("shown.bs.popover",function(){ $(".popover-content input[type=checkbox]").on("click",function(){ if(this.checked) { this.setAttribute("checked","checked"); } else { ...

Certain cases will see success with iPhone jquery/ajax functionality, while others may encounter

I am facing an issue with multiple pages in my project that utilize AJAX to submit a form to django. While the buttons work perfectly on various platforms and browsers like Chrome, Firefox, and desktop Safari, they seem to malfunction specifically on mobil ...

Using Selenium WebDriver in JavaScript to Extract Text from an Array

During my experimentation with Selenium webdriver in javacript, I encountered a challenge when trying to extract text from an array of WebElements (specifically cells within a table). The usual command getText() did not work as expected when attempting to ...

When attempting to access endpoints from other computers, the connection to Express.js is being refused

I have set up an Express server and React for the frontend. The express server is running on port 5000 and React on port 3000. Additionally, I am using JWT tokens for authentication. When I login to the app from the computer it is running on, everything w ...

Retrieving the value of the selected item when it is changed

I am currently using v-select/v-autocomplete in my project: <v-autocomplete v-modal="newRole" :items="roles" label="--Change role--" required return-object item-value="id" item-text=&qu ...

Iterating through a for loop in Angular2 to send multiple GET requests to a Django backend

Currently, I'm facing a challenge with performing multiple GET requests using Angular2 within a Django/Python environment. After successfully making an API request and retrieving a list of users to determine the current user's ID, I utilize a .f ...

Show specific hyperlinks in Django depending on the user group

{% extends 'base.html' %} {% block content %} <p>Welcome to the homepage.</p> <p>{% user.groups.all() %}</p> {% endblock %} Currently, I'm exploring ways to display all the user's groups on the page. Howeve ...

"Utilize the hover functionality in React JS to track the mouse movement

I'm currently facing an issue with a design that involves a 6-column grid and text placed in front of it. The requirement is that when I hover over the text, the background of the corresponding grid column should change to an image. While this functio ...