Scrolling function for an automatically adjusting menu bar

I need help creating a dynamic menu that automatically adjusts in size as the user scrolls down. I found a script online and added it to my HTML file like this:

<script type="text/javascript">
$(function() {
    var header = $(".large");
    $(window).scroll(function() {
       var scroll = $(window).scrollTop();
            if (scroll >= 50) {
            header.removeClass('large').addClass("small");
        } else {
            header.removeClass("small").addClass('large');
        }
    });
});
</script>

In the HTML body, I set the header tag with the default class "large" and left it empty to test the script's behavior.

In the CSS, I styled the header class based on the characteristics of other divs on the page:

header.large{position:fixed; width:100%; height:20%; background-color:#00BFFF; top:0px; left:0; z-index:1;}

header.small{position:fixed; width:100%; height:7%; background-color:#000000; top:0px; left:0; z-index:1;}

Even after changing the color of the small class to verify the script's activation, it still doesn't work. Can anyone provide assistance? Thank you.

Answer №1

The issue lies within this line of code:

var header = $(".large");

If you switch from using the "large" class to the "small" class, this selector will no longer function as expected.

Additionally, it is not necessary to cache this value because the selectors will change based on the new class value.

Using a window function makes the document ready (i.e.: $(function() {) redundant in this case.

I have provided a modified version of the snippet where I replaced 'header' with a div and some text:

$(window).scroll(function () {
      var scroll = $(window).scrollTop();
      if (scroll >= 50) {
        $('.large').removeClass("large").addClass('small');
      } else {
        $('.small').removeClass('small').addClass("large");
      }
    });
    
div.large {
      position: fixed;
      width: 100%;
      height: 20%;
      background-color: #00BFFF;
      top: 0px;
      left: 0;
      z-index: 1;
    }

    div.small {
      position: fixed;
      width: 100%;
      height: 7%;
      background-color: #000000;
      top: 0px;
      left: 0;
      z-index: 1;
    }
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

    <div  class="large">
    bbbbbbbbbbbbbbbbbbbbbbbb<br/>
        
        bbbbbbbbbbbb<br/>
    </div>


    a<br/>
    a<br/>
    a<br/>
    a<br/>
    a<br/>
    a<br/>
    a<br/>
    a<br/>
    a<br/>
    a<br/>
    a<br/>
    a<br/>

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

The document inside the database is displayed in italicized text when it is stored in Firebase

try { // establish a new collection named 'pactLists' const pactListsCollection = collection(db, "pactLists"); // used for storing records of created pacts by users. // generate a unique id for the pact and set it as the invite c ...

Output a MySQL field value into a checkbox by utilizing an if statement

Hey there, I'm really close to getting this statement to work correctly but I just can't seem to figure it out. So I have an overtime field from MySQL and I am able to display it. However, I'm trying to make it either checked or not checked ...

Adding a class to the following DIV and smoothly transitioning the current one out can be achieved using a dynamic number of items in multiple instances

Is there a way to create a scalable CSS slideshow for text divs without using images? Here is the current HTML structure: <div class="mb-panel-container cf"> <div class="mb-panel-section mb-slider"> <div class="mb-panel active" ...

Establish a connection to the current active session using Selenium JavaScript WebDriver

When I'm using Node.js along with the selenium-webdriver package for running my tests, a new session is started and a new window opens each time a test begins. I've been attempting to retrieve the session Id and make use of it later by calling ge ...

Setting a background-image using jQuery in Codeigniter can be done by following these steps

Currently, I am developing a project in Codeigniter. In my jQuery file, I have included code to set the background image of the body element: $('body').css('background-image','url(<?php echo base_url("assets/images/bg2.png");?& ...

Using JavaScript to parse a time string and update it by adding minutes

$.getJSON("api/times", function(times) { var time1 = times.departure; // 14:36:30 (string) var minutesToAdd = parseInt(times.minutesToAdd); // 6 var total = "?"; // How can I add minutesToAdd to time1? }); I need to manipulate the time1 variab ...

`vertical navigation on the left side with expanding submenus`

Trying to create a navigation system on the left side of the page with submenus appearing on the right without impacting the main content. If anyone has any code snippets or resources that can help achieve this, I would really appreciate it. The objectiv ...

ES6 destructuring in a loop

I attempted to extract the father's name from an array of objects and populate a new array with these names. Here is an example: var people = [ { name: "Mike Smith", family: { father: "Harry Smith", } }, { name: "Tom Jones ...

When using selenium-python, every attempt to click a button consistently results in an error message

I've been trying to use Python-Selenium binding to click a button, but I haven't had any luck with various selectors so far. I'm currently using Chromedriver. Although I can select an element using elem = driver.find_element(by='xpath& ...

The code line "npx create-react-app myapp" is not functioning as expected

When running the command 'npx create-react-app my-app', I encountered the following error message: Error: '"node"' is not recognized as an internal or external command, operable program or batch file. Before suggesting to cre ...

Encode a variable into base64 using the Buffer module in node.js

Attempting to convert a variable from an HTTP parameter to base64 using node.js and Buffer. Code snippet: var http = require("http"); var url = require("url"); http.createServer(function(req, res) { var parsedUrl = url.parse(req.url, true); var que ...

What are the best methods for improving the rendering performance of multiple sphereGeometry objects in three.js?

Looking to improve the rendering performance of sphereGeometry in my three.js program, as it is currently a bottleneck. Here is the JavaScript code I am using: var sphereThree = []; for(var idSphere = 0; idSphere < numSphere; idSphere++){ var spher ...

How can you modify the Bootstrap width to activate the responsive design?

I currently have the following HTML code snippet: <!DOCTYPE html> <html lang="en> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale= ...

Passing values between PHP and jQuery using Ajax to compare with a variable is a common task in web development

I'm struggling to get my PHP and jQuery script to work properly. The goal is to pass a value through Ajax, have PHP check it to see if it matches and increment the score by 1. Here is the code I've written: <?php $score = "1"; $userAnswer = ...

Employing a Button with PHP

Here is the code I've been working on: <html> <form action="employee.php"> Enter Employee SSN to Delete:<br> <input type="number" name="ssnDel"> <br> <br> <input type="submit" value="Submit"> </form> ...

Param values not being transferred via AJAX POST request

In my web application using Struts and Velocity, I'm facing an issue where JavaScript needs to pass a parameter to a method in a Java class. I have tried using an AJAX post call to a servlet, but I am not able to receive the parameter in the action cl ...

Steps for configuring jQuery hide(), adding Class, and remove Class for flawless execution

My HTML Code is structured as follows : ... @foreach($hotel as $key=>$value) ... <div class="iteration"> <input type='hidden' value='<?php echo $value['HCode'].'#' ...

Encountering an issue with Firebase Cloud Messaging

I am struggling to implement a push notification trigger whenever a document field is updated. As a newcomer to node.js, I am facing challenges in debugging what seems like a simple function. Below is the code snippet: // Cloud Functions for Firebase SDK ...

When the mouse leaves the area, I would like the iframe within the div to be refreshed

When you hover over the button on the right, a slide panel appears with an iframe. Each time this page loads, it has a different background. I want a new background to load every time there is a new hover, requiring a refresh of the div. How can I achieve ...

Having multiple divs lined up horizontally on a single row

I am trying to create three divs in a single row similar to this: https://i.sstatic.net/A63Sx.png Any assistance on how to achieve this setup would be greatly appreciated. ...