Implement a jQuery function that dynamically adds a CSS attribute when the user scrolls

I am attempting to implement an on-scroll function that will add a CSS background color attribute to the menu when the user scrolls to a certain point.

However, I am encountering difficulties. I have double-checked the scroll function usage and ensured that the syntax is correct, but the CSS() jQuery function does not seem to take effect as shown in this codepen.

How can I modify the CSS attribute once the user scrolls to a specific point on the screen?

$(document).ready(function() {
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if (scroll >= 100) {
      $(".top-nav").css('background', 'blue');
    } else {
      $(".top-nav").css('background', 'transparent');
    }
  });
});
html,
body {
  box-sizing: border-box;
  font-family: Arial, Helvetica, sans-serif;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: scroll;
  overflow-x: hidden;
}
/* Rest of the CSS code block remains unchanged */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Rubik:wght@500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@600&display=swap" rel="stylesheet">
<script src="https://use.fontawesome.com/releases/v5.0.10/js/all.js"></script>
<div id="grid-wrapper" class="wrapper">
  <nav class="top-nav">
    <h1> 
       /* HTML navigation bar content remains untouched */
    </nav>
  <div id="side-menu" class="side-nav">
      /* Side menu content remains normal */
  </div>
</div>
<div class="main"></div>

Answer №1

There seems to be an issue due to the presence of a overflow: scroll property on the body element, which prevents scrolling within the window. Instead, the scrolling behavior is applied to the body itself, causing the event handler to be attached to the wrong element.

Furthermore, it's recommended to avoid mixing CSS styling (and even HTML) directly in JavaScript code. A better practice is to define CSS classes for styling and apply them dynamically using functions like toggleClass(). Consider implementing the following approach:

jQuery($ => {
  $('body').scroll(function () {
    var scroll = $(this).scrollTop();
    $('.top-nav').toggleClass('blue', scroll >= 100);
  });
});
[CSS STYLING CODE HERE]
[JS SCRIPTS AND HTML ELEMENTS HERE]

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

What is the most efficient way to perform an inline property check and return a boolean value

Can someone help me with optimizing my TypeScript code for a function I have? function test(obj?: { someProperty: string}) { return obj && obj.someProperty; } Although WebStorm indicates that the return value should be a boolean, the TypeScript compil ...

Is there a way to control a single Angular application using multiple JavaScript scripts?

Summary: I am looking for a way to allow two script files to handle different tasks within the same angular app. One needs to initialize the app, while the other needs to assign a templateCache object to a section of JSON stored in localStorage. Backgrou ...

Substitute the text within a personalized tag with the provided content

Need help with a dynamic string <li>&emsp;Content Test 1</li>. Looking for regEx solution to replace tags so the final output is <ul><li>Content Test 1</li></ul> (Removing &emsp and adding <ul> while pr ...

Monitoring Clicks within an Iframe

Is there a way to track a click event on a hyperlink within an iframe using Google Analytics? The iframe is located within the same domain as the main page. How can this be achieved? The iframe is added dynamically to the page after it has loaded. Is i ...

Merging two distinct arrays of objects in JavaScript can be achieved by utilizing various methods and

I have a challenge where I need to merge two arrays of objects in a nested way. var array1=[{ PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2& ...

Implementing a JQuery click method within a class structure

I'm having trouble getting the functionality of the .click function to work on my page unless I paste it into the browser console. In my class, this is what I have: var myClass = function(){ var toggleChecked = function(){ $('#myCheck ...

JavaScript Magic: Hide Div when Clicking Away

I need a solution where clicking outside of the My DIV with the ID Container_ID will hide all elements within the Container by setting their style to display: none;. Currently, the JavaScript code I am using partially achieves this functionality, but it al ...

Summon wicket from the non-wicket-component entity

I am currently utilizing js-lib to transform text into a rich-editor, complete with options such as "bold", "italic" and more. The RichEditor also includes an UploadImage button, for which I am able to modify the call-back function: function startUploadi ...

Guide on exporting a function from Node.js and utilizing it as middleware

Within my middleware directory, there is a file named auth.js. This file contains the following function: function authCheck() { if (req.session.loggedin) { return; } else { req.session.destory(); res.redirect('/login'); } } I ...

What is the best way to manage errors and responses before passing them on to the subscriber when using rxjs lastValueFrom with the pipe operator and take(1

I'm seeking advice on the following code snippet: async getItemById(idParam: string): Promise<any> { return await lastValueFrom<any>(this.http.get('http://localhost:3000/api/item?id=' + idParam).pipe(take(1))) } What is the ...

Conceal different text when a div with a specific class includes particular text

Is there a way to dynamically add a class to a div based on the content of another div on the same page? Here is a snippet of my HTML: window.addEventListener("load", () => { let b = document.getElementsByClassName('aw-property-data-item') ...

Changing boolean values to integers

I am trying to save values in a MySql field of type tinyint(1) that have already been converted from boolean using php's intval(). For example: $data = true; $foo = intval($data); if (is_numeric($foo)){ print_r($foo); } The i ...

Concentrate on a specific input within a list of inputs that are generated dynamically

My list contains dynamically generated inputs. input --> onClick new Input beneath [dynamically added]input input How can I focus on just the dynamically added input? The input has the textInput reference. This code partially achieves it: componentW ...

What are the ways in which I can implement that code with a pair of dropdown menus?

Is it possible to use this code with two dropdown menus? Currently, when I reload the page, the first dropdown menu retains its desired state, but the second one does not. Thank you for any help, I apologize for the beginner question as I am new to this am ...

What is the best way to retrieve data from a jQuery $.post() request?

I'm currently facing a challenge where I am attempting to send a post request using JQuery, but I am encountering difficulties in extracting the data on a server built with Express. In my current approach, I have been attempting to send data using th ...

Adjusting the width of speech balloon in CSS

This question might seem basic to those who are familiar with CSS (unlike me lol). I'm currently working on incorporating speech balloons into my website using this code from jsfiddle. However, I encountered an issue when the text inside the balloon i ...

Ensure that any portion of a child DIV becomes visible only if it falls within the confines of the parent DIV, even if the overflow:hidden property is

My inner div can be resized by the user, and I have it inside another div. The issue is that when the inner div extends beyond the outer div, it covers it completely, or I have to use overflow:hidden, which hides the outer edges of the inner div. Ideally, ...

Transforming the *.vue file into a *.js file for deployment on a content delivery network

Is there a way to compile Component.vue files into JavaScript files for use with the Vue CDN in HTML? For example, consider the following component Component.vue: <template> <div class="demo">{{ msg }}</div> </template& ...

Tips for transferring data when clicking in Angular 5 from the parent component to the child component

I need assistance with passing data from a parent component to a child component in Angular 5. I want the child component to render as a separate page instead of within the parent's template. For example, let's say my child component is called & ...

Sorry, but we are experiencing difficulties processing your request at the moment. HTTP ERROR 500: We are unable to locate the

My code seems to be functioning correctly when connecting to the database, but I'm encountering an error. Here is the code snippet: <?php include 'header.php'; ?> <!DOCTYPE html> <html> <head> <t ...