Tips for keeping the Menu bar at the top of the page while scrolling from the middle

I came across a technique mentioned here that I wanted to implement. I used this jsfiddle link (which worked well) to create my own version http://jsfiddle.net/a2q7zk0m/1/, along with a custom menu. However, now it seems like it's not working due to a possible JavaScript error:

$(document).ready(function() {
    $(window).scroll(function(e) {
        $el = document.getElementById('temp');
        if ($(this).scrollTop() > 100) {
            $el.addClass("fixedNav");
        } else {
            $el.removeClass("fixedNav");
        }
    });
});

It seems the script is having trouble recognizing the ID of the div and accessing the CSS class. Unfortunately, I can't use the class attribute here. Can anyone help me troubleshoot this issue? Thank you!

Answer №1

Revise this line:

$el = document.getElementById('temp');

to this:

$el = $('#temp');

JSFiddle


You can also wrap the $el in a jQuery object:

$el = document.getElementById('temp');
// ...
$($el).removeClass("fixedNav");

JSFiddle


Additionally, it is recommended to declare $el outside of the $(window).scroll method to avoid searching for the element in the DOM while scrolling.

$(document).ready(function(){
    var $el = $('#temp');
    $(window).scroll(function (e){
        if ($(this).scrollTop() >= 100 && !$el.hasClass("fixedNav")) {
            $el.addClass("fixedNav");
        }else if($(this).scrollTop() < 100 && $el.hasClass("fixedNav")){
            $el.removeClass("fixedNav");
        }
    });
});

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

sending information from a PHP form to a JavaScript window

Currently, I am in the process of developing a game using javascript and jquery. In this game, when a player interacts with another character, it triggers the opening of text from an external file using the window.open('') function. At the start ...

The canvas is being expanded by utilizing the drawImage method

Ensuring the correct size of a <canvas> element is crucial to prevent stretching, which can be achieved by setting the width and height attributes. Without any CSS applied other than background-color, I am faced with an unusual issue. Using ctx.draw ...

"Exploring the various configurations for session handling in NodeJs

I am trying to implement a login system using the express-session module. I'm unsure if I have set everything up correctly, especially when it comes to the secret option. Currently, my initialization code for express-session looks like this: app.use( ...

Express server does not send any response body

When a request is made to my express application, it returns an empty {}. const express = require('express'); const bcrypt = require('bcrypt'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyPar ...

What steps should be taken in order to ensure the effectiveness of this keyword search

Currently, I am attempting to implement a keyword search feature for my meteor web app. Although the functionality is there, it's running quite slow. The way it works now is that when a user creates an article, they assign keywords to it. The keyS fun ...

Retrieving values from multiple Select components in Material-UI is key

I have encountered an issue with my two MUI Select components on the page. I am attempting to set values based on the id of the Select component. Initially, when I check (id === "breed-select") in the console, it returns true, but shortly after ...

What is an alternative way to show the contents of a JSON file without directly accessing it

Recently, I stumbled upon an amazing website - where I have been exploring to learn something new. The website prominently features the use of Ajax and some fascinating javascript without any additional libraries. Within a single javascript file on this ...

Tips for making a dropdown menu within an Ionic Side menu

Looking for guidance on creating a sub menu in the ionic framework? I'm new to AngularJS and ionic framework, but eager to learn. Below is the code snippet I used to create a dropdown list component: <ion-side-menu side="left"> <ion-co ...

What is the best way to extract specific values from a JSON array of objects using JavaScript?

I am facing some challenges in displaying values from the AJAX objects. My goal is to populate a select box with names using AJAX, but I seem to have made an error somewhere in my code. Can someone please assist me in identifying and correcting the mistake ...

Place the outcome of the function into the div element's attribute

As a newcomer to HTML and JavaScript, I recently dove into using 3Dmol.js. Following a tutorial, I was able to create this code snippet that actually works: <script src="http://3Dmol.csb.pitt.edu/build/3Dmol-min.js"></script> <div id="el ...

What is the best method to reset values in ngx-bootstrap date picker?

At the moment, it is only accepting the most recently selected values. To see a live demo, click here. ...

Error: The name property is not defined and cannot be read in the Constructor.render function

Having trouble building a contact form and encountering an error when trying to access the values. I've checked for bugs in the console multiple times, but it seems like something is missing. Can anyone provide assistance? var fieldValues = { ...

Disable default behavior in a SharePoint 2010 List new form with jQuery if conditions are not met

In the SharePoint 2010 List new form, there are 10 checkboxes available. I specifically need to choose exactly 3 of them and not less than that. Even though I implemented jquery for this purpose, it seems that the form does not stop submitting when the con ...

Ways to create two distinct "on click" actions for a single image to execute two distinct tasks

Clicking on an image will open a slider showing all images before filtering. Once filtered, only the selected images will be displayed in the slider. <div class="gallery row" id="gallery" style="margin:0;"> <!-- Grid column --> <div ...

"Angular File Upload Made Easy with Drag-and-Drop Functionality and Cleverly Positioned

Encountering an issue with Angular File upload in conjunction with relatively positioned elements. The drop target is set to 100% width and height, absolutely positioned. While dragging a file over any non-relatively positioned element, the overlay functio ...

A Step-by-Step Guide to Clearing JSON Cache

I'm currently utilizing jQuery to read a JSON file. However, I've encountered an issue where the old values are still being retrieved by the .get() function even after updating the file. As I continuously write and read from this file every secon ...

Resize a group of images to match the parent's width and height dimensions

I am working with a div that contains variously-sized images and is nested inside a parent container. <div id="parentContainer"> <div id="boxToScale"> <img src="http://placehold.it/350x150" /> <img src="http://placehold.it/150 ...

What is the method for identifying the environment within an Express.js application?

Is there a reliable method for determining the environment in which an expressJS app is currently operating (development, test, production)? I have checked process.env, but found no clear indication of the environment. I know that variables can be set in ...

"Maximizing the functionality of HTML forms by incorporating PHP for efficient data retrieval

I have been exploring different approaches but I'm struggling to get this to function correctly. As a beginner, I am using form elements with dropdown menus to receive user input and then send the data via email. Here is the HTML and PHP code: <fo ...

Redux Persist causes the redux state to become undefined

I recently added redux-persist to my project and now I am facing an issue where all of my Redux states are returning undefined. Previously, all the Redux states were functioning properly. However, after incorporating redux-persist, they are no longer work ...