Updating the color of the hamburger menu based on the scroll position using an event listener

Is there a way to change the color of my burger bar lines using event listeners? I'm trying to target the spans that make up the burger menu lines by assigning them a class "span". Here's what I have:

 var distFromTop = document.querySelector(".om-mux").offsetTop;
 var distFromTop2 = document.querySelector(".galleri").offsetTop;
 var distFromTop3 = document.querySelector(".event-sektion").offsetTop;

 window.addEventListener("scroll", function() {
     var scroll = this.scrollY;
     if (scroll > distFromTop && scroll < distFromTop2) {
         document.querySelector(".span").style.backgroundColor = "black";
     } else if (scroll > distFromTop2 && scroll < distFromTop3) {
        document.querySelector(".span:before").style.backgroundColor = "white";
     } else if (scroll > distFromTop3){
        document.querySelector(".span").style.backgroundColor = "black";

     } else {
        document.querySelector(".span").style.backgroundColor = "white";

     }
 })`

The code is working fine, but it only changes the style of the middle span because the upper and bottom lines are styled like this:

`  .menu-btn > span,
  .menu-btn > span::before,
  .menu-btn > span::after {
    display: block;
    position: absolute;
    width: 100%;
    height: 2px;
    background-color: #ffffff;
    transition-duration: .25s;
  }`

How can I target span:before & span:after elements? Can I achieve this with something like:

        document.querySelector(".span:before").style.backgroundColor = "white";

Answer №1

Although English is not my native language, I ask for your understanding. Consider applying a new class to a span element when scrolling and assigning a background-color property to that class in your CSS stylesheet. For instance:

Instead of using this:

document.querySelector(".span").style.backgroundColor = "black";

Try the following approach:

document.querySelector(".span").classList.add('black');

Then, include this class with its corresponding CSS properties in your stylesheet:

.menu-btn > span.span.black::before{
    background-color: #000;
}

Answer №2

source: Manipulating CSS pseudo-element styles with JavaScript

The technique closest to modifying the style of a pseudo-element using JavaScript involves adding and removing classes, followed by utilizing the pseudo-element with those classes. For instance, here's an example to conceal the scrollbar:

CSS

.hidden-scrollbar::-webkit-scrollbar {
   visibility: hidden;
}

Javascript

document.getElementById("editor").classList.add('hidden-scrollbar');

If you wish to subsequently eliminate the same class, you can use:

document.getElementById("editor").classList.remove('hidden-scrollbar');

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

Convert your Airbnb short link into the full link

I am currently developing an application that utilizes Airbnb links as part of its input. So far, I have identified two types of links: Long form, for example: . These are commonly used on desktop. Short form, such as: . These shorter links are often shar ...

Most Effective Method for Directing Users to Mobile Website

How do you prefer to guide users to a custom mobile site, such as redirecting from mysite.com to m.mysite.com or mysite.com/m? I previously experimented with the Detect Mobile Browsers JS solution, which seemed promising. However, I noticed that it initia ...

Cross-Origin Resource Sharing (CORS) Issue: How Angular.JS, Node.JS, and

Encountering problems retrieving data from a http post request to my API. Seeing the following error message: XMLHttpRequest cannot load (URL to API here). No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin &ap ...

Accessing specific documents in Firebase cloud functions using a wildcard notation

Currently, I am working on implementing Firebase cloud functions and here are the tasks I need to achieve: Monitoring changes in documents within the 'public_posts' collection. Determining if a change involves switching the value of the &ap ...

Select the input based on the name and value provided from a radio button using jQuery

I want to show a div element when the user chooses option 4 from a radio button. $(document).ready(function () { $("#GenderInAnotherWay").hide(); $("input[name='Gender'][value=4]").prop("checked", true); $("#GenderInAnotherWay").tog ...

The electron program is unable to locate the package.json module

I am new to electron and attempting to run an express app for the first time. However, I encountered this error: Need assistance updating code Error: Cannot find module 'C:\package.json' at Module._resolveFilename (module.js:440:15) ...

One div is experiencing trouble with the `align-items: center` property, while the other divs are functioning

Presenting my React component: <div className='sidebar'> <div className="sidebarItem"> <span className="sidebarTitle">About Me</span> <img src="https://wallpapera ...

Tips for streamlining the JSON parse object prototype in JavaScript

I recently had a JavaScript object that was created without a prototype. let bar = Object.create(null); After reading and parsing a JSON file in Node.js, I reassigned the parsed data to bar. Here's how: fs.readFile('data.json', 'utf8 ...

Encountering difficulty in assigning the desired value to the select box

// updating the subType value in the controller $scope.newEngagement.subType = 3; // creating a list of engagement subTypes $scope.engagementSubTypeList = [ { "subTypeId": 1, "subTypeName": "value1" }, { "subTypeId": 2, "subTypeName": "value2" }, { " ...

What could be causing my border to spill over into the adjacent div?

Trying to set up the contact section of my portfolio but running into an issue where the border of one div is overflowing into the next. Here's a snippet of the code: //CSS .contact-cont { padding: 4rem 12rem 0rem; height: 90vh; ...

Ways to invoke foo specifically when either a click event or a focus event is triggered

In my custom directive, I am binding focus and click events to an element: app.directive('mydirective', function () { return { link: function ($scope, $element, $attrs) { $element.bind('click focus', function (e) { f ...

Converting a nested JavaScript array into a PHP array

Having a javascript array is how my dilemma starts: foodList = ([apple,10,],[banana,20]) To convert this to a json object and send it to php, I perform the following action: var jsonData = JSON.stringify(foodList); The challenge now is extracting values ...

Creating functional dropdown menus with popperjs in the latest Bootstrap version 5

Currently, I am attempting to implement dropdown menus in Bootstrap 5. According to my research, this feature requires Popper.js integration, but I am uncertain of the correct way to include it in my Laravel project that utilizes Laravel Mix. I have made ...

Creating a dynamic CSS hover animation for an input element with jQuery to ensure compatibility with Microsoft Edge

I am facing an issue where I have a row of six to nine switches with the <input type="checkbox"> element, and each switch animates when hovered over. In this animation, the knob slides down, and both the knob and track fill with colors or gradients. ...

JavaScript - Marking selected text: What are the options?

I am looking to implement a feature in JavaScript (without jQuery) that will allow me to highlight selected text with control points or markers (left and right). These markers should function similar to those on mobile phones, allowing me to extend the sel ...

Creating a custom JavaScript clock based on stored database values

I am looking to create an analog clock using JavaScript. I have both working hours and off hours stored in a database. My goal is to display working hours in one color and off hours in another color on the clock. How can I achieve this? The database prov ...

The mysterious height phenomenon when setting the width of a list item with jQuery

Consider a basic ul and li setup similar to this: <div id="middle"> <ul> <li> <a> bridal </a> </li> //.... </ul> </div ...

Tips for extracting the two characters following a space in a string with or without the use of regex

How can I extract only the initials of 2 characters after spaces? See the code snippet below: const name = "John Peter Don"; const result = name.match(/\b(\w)/g).join(''); console.log(result)// JPD->> i want only JP ...

Using jq and node.js to translate AWS EC2 tags

Seeking assistance with transforming this array of EC2 tags using jq and node.js: [ { Key: 'Name', Value: 'xxx' }, { Key: 'role', Value: 'yyy' } ] I want to transform it to: { name : 'xxx', ro ...

Invoke a Python function from JavaScript

As I ask this question, I acknowledge that it may have been asked many times before. If I missed the answers due to my ignorance, I apologize. I have a hosting plan that restricts me from installing Django, which provided a convenient way to set up a REST ...