Transitioning from a see-through navigation bar to a vibrant colored menu as

I consider myself a novice when it comes to JavaScript. My goal is to create a Transparent Menu that smoothly transitions from transparent to white with a box shadow as I scroll down the page. However, the JavaScript code I have implemented does not seem to be working.

<script type="text/javascript">
var a=document.getElementById('play');
var x=window.pageYOffset;
var see =function () {
    if (x >30) {
        a.style.background=" white";
    }else{
        a.style.background="transparent";
    }
    window.addEventListener("onscroll",see);
}
</script>
<header>
        <div class="menu" id='a'>
            <ul>
                <li><b>About</b></li>
            </ul>
        </div>
    </header>
.menu {
  background: transparent;
  margin-left: 320px;
  text-align: center;
  width: 100%;
  padding: 20px;
  position: fixed;
  top: 0px;
  transition: .5s;
}

Answer №1

  • Ensure that the x definition is placed within the see function
  • Remember to put
    window.addEventListener("onscroll", see);
    after (outside) the see function
  • Utilize the Event name "scroll"
var a = document.getElementById('play');

function see() {

  var x = window.pageYOffset; // This should be inside
  
  if (x > 30) {
    a.style.background = " white";
  } else {
    a.style.background = "transparent";
  }
}

window.addEventListener("scroll", see); // This should be outside

Additionally, keep styling within CSS files instead of scattered throughout your JS files.
Make use of Element.classList.toggle() to switch a pre-defined CSS class:

const EL_play = document.querySelector("#play");

function see() {
  var x = window.pageYOffset; // This should be inside
  EL_play.classList.toggle("is-active", x > 30);
}

window.addEventListener("scroll", see); // This should be outside
body {
  margin: 0;
}

#play {
  position: sticky;
  top: 0;
  width: 100%;
  transition: background-color 0.3s;
}

#play.is-active {
  background-color: gold;
}
<div id="play">PLAY</div>
<p style="height: 300vh;">Long element to force scrollbars...</p>

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

Using AngularJS Services to Share Objects Between Views and Controllers

I'm finding it difficult to grasp the concept of AngularJS services as I am fairly new to AngularJS. My goal is to pass a nested object between two controllers/views. In my home page partial, I have a section that displays the project and task. hom ...

Unintentional GET request triggered by Axios baseURL

I have encountered a strange issue where defining axios.defaults.baseURL = baseUrl; results in an unexpected GET request right after initializing my Vue app. Any assistance would be greatly appreciated! Below are images showing the code and network reques ...

The useNavigate() hook from react-router-dom is not properly setting the id in the URL path

I am currently using react-router-dom v6 for my routing needs. My goal is to pass an ID in the navigate URL path. Here is the onClick method and button code that I am working with: let navigate = useNavigate(); const routeChange = (id) => { let ...

Grails: Javascript function for updating the image source is unresponsive

I have a situation where I need to change the src of an img based on a certain condition. The condition is returning true as expected, as confirmed by an alert() that I added previously. However, the function responsible for changing the src of the img and ...

Utilize JavaScript when sharing on social media to avoid the possibility of embedding the entire

This javascript code snippet is extracted from www.twitter.com (simply click to view the source code). I have reformatted it for better readability: if (window.top !== window.self) { document.write = ""; window.top.location = window.self.location; s ...

What does the term "root element" refer to in the Material-UI documentation?

I am finding the terminology used in material ui confusing and would appreciate if someone could clarify it for me. For example, let's consider this information from https://material-ui.com/guides/api/: Spread Undocumented properties supplied ar ...

Is there a way to enable popovers globally and also utilize the container: 'body' option simultaneously?

My Bootstrap 5 popovers seem to be missing the arrow and I suspect it's because of interference from the parent element. The documentation provides a solution by using the container: 'body' option on a single item. How can I apply this to al ...

Search timeout restriction

I have a function that makes a request to the server to retrieve data. Here is the code for it: export default class StatusChecker { constructor() { if (gon.search && gon.search.searched) { this.final_load(); } else { this.make_req ...

Add HTML content individually to each item in the array

I am currently developing a plugin and I need to load a preset in order to populate a form with the relevant data. In an attempt to write concise code, I created a variable called "template" that looks like this: var Fields = '<div c ...

Guide on centering an unfamiliar element in the viewport using HTML, CSS, and JavaScript

In the process of developing my VueJS project, I have successfully implemented a series of cards on the page. However, I am now facing a challenge - when a user selects one of these cards, I want it to move to the center of the screen while maintaining its ...

Is it possible to achieve the same functionality as :first-child by employing :nth-of-type without a selector?

Currently tackling a console warning related to MUI5/emotion (I believe) I have noticed that the pseudo class ":first-child" might pose potential risks during server-side rendering. It may be worth considering replacing it with ":first-of-type". I wonder ...

Is it possible to access Firebase data in Vue.js, with or without Vuefire, using a router parameter before the DOM is rendered?

When I navigate to a view from another view, I pass the itemId as a param value to vue router. My goal is to call firebase with that itemId in order to filter the data and use the filtered result/data in the UI. Specifically, I am utilizing vuefire. The ...

Guide to verifying a field's value in a database

My web application requires three inputs from the user: UserName, FirstName, and Email. The goal is to verify if the entered username exists in the database and if so, validate the corresponding Firstname and email. If all three values are correct, a succ ...

Challenges encountered when attempting to access files from the filesystem on vercel

Currently, I am working on a website that includes a "blog" section with markdown files. The setup reads the files seamlessly from the file system without any errors... except when deployed on Vercel. In that case, it throws a "No such file or directory" e ...

Is there a way to ensure seamless animation when dynamically adding components in react native?

I am working on a React Native application where I have implemented a card with a conditional <Text> component. This text is rendered when a button is pressed and removed when the same button is triggered again. Below is a snippet of my code: <V ...

Making a node.js API call using multipart/form-data

Submitting Data Using POST https://i.sstatic.net/iVTDd.png Node.js Data Capture Method without the Use of Express and Body-Parser FORM DATA: ORDERID: MID: TXNID: TXNAMOUNT: 5.00 PAYMENTMODE: NB CURRENCY: INR TXNDATE: 2021-06-14+23%3A02%3A30.0 STATUS: ...

Browsing through the last items on a webpage

I have set up a jsfiddle that explains itself quite well: http://jsfiddle.net/nt7xzxur/ with the following smooth scrolling code: function smoothScroll(hash) { $('html, body').animate({ scrollTop: $(hash).offset().top }, 750); By clicking o ...

Tips for adding an image into a PDF document using the jsPDF library in HTML

Due to the lack of support for utf8 characters in jspdf, I'm experimenting with replacing some characters with images before exporting to pdf. To illustrate, I've created a code sample where I insert an image into an html div and then attempt to ...

Is there a way to modify the color scheme of my webpage while utilizing Bootstrap?

As I delve into programming with Bootstrap, I encountered an issue while attempting to change the background color of my body. Even though I used the following CSS code: body { background-color: #eba; width: 100%; height: 100%; } The color change ...

What could be causing the malfunction of removeEventListener in my Nuxt application?

Whenever a search result is displayed on my app, the component below renders and checks if the user scrolling is at the bottom of the page. Initially, the code works fine, but I encounter an error when returning to the page after navigating away and scro ...