Modify the color of SVG for various sections

I'm looking to create a dynamic hamburger menu that changes color based on different sections of the page. I've experimented with a few approaches, but encountered some issues - the first attempt only works when scrolling down, and the second attempt only affects the first two sections.

<div class="nav">
  <svg class="burger" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="32px" id="Layer_1" style="enable-background:new 0 0 32 32;" version="1.1" viewBox="0 0 32 32" width="32px" xml:space="preserve">
  <defs>
....
});

CSS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
....
});

JS attempt 1 ( codepen- https://codepen.io/tarunpatnayak/pen/rNYQpwL)

const mSections = document.querySelectorAll("section");
....
});

JS attempt 2 (codepen - https://codepen.io/tarunpatnayak/pen/JjOeMJJ )

const mSections = document.querySelectorAll("section");
....
});

JS attempt 3 (jQuery)(codepen - https://codepen.io/tarunpatnayak/pen/VwrVrba )

var dOffset = $("[data-id = dark]").offset();
....
});

Answer №1

When it comes to creating effects, sometimes simplicity is key. If you don't absolutely need to use SVG and JavaScript, opting for a combination of basic HTML and CSS can suffice. One interesting method to achieve certain effects is by utilizing the 'mix-blend-mode' property. Check out this example for more insight: https://codepen.io/noye/pen/QWOJmvr.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  transition: background 1s ease-in-out;
}

#menuToggle
{
  display: block;
  position: fixed;
  top: 50px;
  left: 50px;
  z-index: 1;
  mix-blend-mode: difference;
  -webkit-user-select: none;
  user-select: none;
}


#menuToggle span
{
  display: block;
  width: 33px;
  height: 4px;
  margin-bottom: 5px;
  position: relative;
  background: white;
  border-radius: 3px;
  z-index: 1;
}

.section {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  color: #000;
  font-family: sans-serif;
  font-size: 72px;
  font-weight: 600;
  text-transform: uppercase;
    
}

[data-id = "dark"]{
  background:black;
  color:white;

}

[data-id = "light"]{
  background:white;
  color: black;
}
<nav role="navigation">
  <div id="menuToggle">
    <span></span>
    <span></span>
    <span></span>
  </div>
</nav>
<section class="section dark"  data-id="dark">
One</section>
<section class="section light" data-id="light">Two</section>
<section class="section dark"  data-id="dark">Three</section>
<section class="section light" data-id="light">Four</section>
<section class="section dark"  data-id="dark">Five</section>
<section class="section light" data-id="light">Six</section>
<section class="section dark"  data-id="dark">Seven</section>
<section class="section light" data-id="light">Eight</section>

Answer №2

I managed to solve this issue independently

For those interested, here is the code snippet

jQuery Version ( https://codepen.io/tarunpatnayak/pen/VwrVrba )

var dSection = document.querySelectorAll(".dark");
for (var i = 0; i < dSection.length; i++) {
  dSection[i].setAttribute("data-hcolor", "white");
}
var lSection = document.querySelectorAll(".light");
for (var i = 0; i < lSection.length; i++) {
  lSection[i].setAttribute("data-hcolor", "black");
}
$(document).ready(function () {
  $(window)
    .scroll(function () {
      var scrollDistance = $(window).scrollTop();
      $(".section").each(function (i) {
        var hColor = $(this).data("hcolor");

        if ($(this).position().top <= scrollDistance) {
          $("svg.burger").css("stroke", hColor);
         // console.log($(this));
        }
      });
    })
    .scroll();
});

JS version ( https://codepen.io/tarunpatnayak/pen/mdqQvoJ )


document.addEventListener("scroll", () => {
  var mSections = document.querySelectorAll(".et_pb_section");
var Hsvg = document.querySelector("svg.burger");

var dSection = document.querySelectorAll(".dark");
for (var i = 0; i < dSection.length; i++) {
  dSection[i].setAttribute("data-hcolor", "white");
}
var lSection = document.querySelectorAll(".light");
for (var i = 0; i < lSection.length; i++) {
  lSection[i].setAttribute("data-hcolor", "black");
}
  
  
  let mCurrent = "";
  mSections.forEach((mSection) => {
    const mSectionTop = mSection.offsetTop;
    const mSectionHeight = mSection.clientHeight;
    if (pageYOffset >= mSectionTop * 0.97) {
      mCurrent = mSection.getAttribute("data-hColor");
      Hsvg.style.stroke = mCurrent;
    }
  });
  console.log(mCurrent);
});


I hope this information proves useful to you. Wishing you a pleasant day ahead.

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 instantiate FormData with the constructor

Within my Angular application, I have a basic form setup like this: <form [formGroup]="loginForm" (submit)="login()"> <div id="container-credentials"> <input type="text" name="username" formControlName="username"> <input typ ...

Ways to access Angular controllers from various folders

Yesterday, I dove into learning my first node.js/MEAN application and stumbled upon this helpful tutorial to kick-start my journey: https://scotch.io/tutorials/creating-a-single-page-todo-app-with-node-and-angular After following the tutorial and successf ...

Discovering nearby intersections within 2 sets of arrays

Imagine having these two arrays: var a = [126, 619, 4192, 753, 901]; var b = [413, 628, 131, 3563, 19]; Is there a way to identify elements in both arrays that are close to each other by a certain percentage? Let's say we have the following functio ...

Move a Java application from a trial SAP HCP to a complete SAP HCP membership

After successfully creating a Java IoT App with Raspberry Pi running on SAP HANA HCP trial account, I am now looking to enhance its functionality within the SAP HANA Development Workbench. Is there a way to import it into the SAP HANA account with ease, o ...

What is the best method for calculating the total of a mongoose attribute?

I am attempting to calculate the sum of schema using reduce. However, the current code is not adding the items together but rather placing them next to each other. For example, 20 + 30 should result in 50, but instead it gives me 02030. Is there an issue w ...

Struggling to access the ref object of a Child Component in React JS parent component

I need to access properties like getBoundingClientRect() and scrollTop from the <div> and <span> components in the ChildComponent, but I want to do it in the Parent component. Here's how I attempted it: class Parent extends Component { ...

The custom pagination feature on WordPress is not functioning as expected

I've been working on a WordPress project recently and I encountered an issue with the custom pagination I implemented. Everything works fine when navigating to pages 2, 3, etc., but when trying to go back to the first page by clicking on the '1&a ...

The invokeApply parameter within $interval remains unchanged and has no effect

In the documentation for AngularJS's $interval service, it is mentioned: invokeApply (optional) boolean: If set to false, skips model dirty checking. Otherwise, will invoke the function within the $apply block. This implies that setting invokeApp ...

How can JQuery be utilized to extract the information stored in the "value" parameter of a chosen option?

I have a dropdown menu that dynamically populates its options with numbers. Here is the code for that: <select name="TheServices" id="services-selector"> <option value="" disabled selected hidden>Static Select ...

Delaying Jquery on scroll Event

Hey there, I've got a set of icons that I'd like to reveal one by one as you scroll down. I've incorporated some animations from , but now I'm wondering how I can implement a delay function in my jQuery so the icons appear sequentially ...

Is there a way for me to convert my (TypeScript Definition) .d.ts file into a (JavaScript) .js file?

It seems that there are plenty of guides available on converting a file from .js to .d.ts, but not the other way around. Specifically, I have some code in .d.ts format and I would like to convert it into JavaScript. Can anyone offer assistance with this t ...

JavaScript: converting to string

Why does Object.prototype.toString === toString? When I include the following code in the global scope: var toStringValue = toString.call("foobaz"); I assume that toStringValue would be the value of window.toString since window is the default scope, corre ...

Incorporating a JavaScript npm module within a TypeScript webpack application

I am interested in incorporating the cesium-navigation JavaScript package into my project. The package can be installed via npm and node. However, my project utilizes webpack and TypeScript instead of plain JavaScript. Unfortunately, the package is not fou ...

css code for styling html elements

HTML: <link rel="stylesheet" type="text/css" href="styles.css"><table border="0" cellpadding="0" cellspacing="0" class="month"> <tr><th colspan="7" class="month">January 2017</th></tr> <tr><th class="mon">Mo ...

Issue with page not updating after local storage change and returning to previous page

I have encountered an issue where in Firefox and Safari, the value retrieved from localstorage on the first page is not updated until I manually refresh the page after setting the localstorage value on the second page. Disabling the cache did not resolve t ...

Does the Loopback Model have an "exists" method that includes a where clause?

I am interested in querying the data using filters to check for existence. Does loopback support this method of querying? If so, could you provide some guidance? myModel.exists({where: {and: [{city: "London"}, {gender: "F"}]}}, function(err, bool){ if(bo ...

The PHP script is not receiving the post parameters sent in the ajax request

Help Needed jQuery.ajax({ url: 'PHPdocs/appsearch.php', data: {term:'blub'}, type: "POST", async: true, data: "text", succes ...

What is the best way to send my webform data to a web API controller as a model class using JQuery AJAX?

This is the AJAX code I have written to pass two values to my API: function submitData() { var username = $("#username").val(); var password = $("#password").val(); $.ajax({ type: 'POST', ...

Can someone show me the JavaScript code to split a string at every instance of ' '?

Hey there! I have a question about manipulating strings. Take a look at this example: var string = '"In Another World" "Magic Books"' I want to create an array that contains every name within the [""]. How can I ach ...

AngularJS magic: display content with ng-show as objects load

My webapp is built using AngularJS and Firebase for user authentication. Each user has an email in their profile, and I want to show a warning if the email is not set. However, when a user logs in and their email is set, the warning briefly flashes at the ...