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

The functionality of classes containing <ul> elements is ineffective

Having recently embarked on the journey of learning html/css, I've encountered some confusion along the way. Allow me to showcase my basic web-page layout: <html> <head> <meta charset="utf-8"> <link rel = "stylesheet" type="text ...

Iterate through each element in the array and manipulate the corresponding data

I am trying to figure out a way to assign a unique id to each item in an array and send it to the "script.js" file for individual data processing. <script href="script.js"></sciprt> script.js: $(function(){ $('#box' ...

Preserving classes in JQuery after making AJAX requests

Before we proceed, it's important to note that I am unable to modify any of the existing calls, code, or functions. This means I must come up with a workaround solution. So, here's the situation: I have a form containing various fields and a dro ...

What is the significance of the "component" prop within MUI components?

I am a beginner in React and HTML. Currently, I am using MUI and React to create my own website. I am currently attempting to add an "Upload button" that will allow me to select an image file when clicked. Below is the official implementation: <Button ...

Tips for utilizing jQuery or AJAX to automatically update a div every 10 seconds

Seeking assistance from fellow developers. Working on a PHP web app utilizing the Yii MVC framework and its array of tools. Specifically, I am looking to dynamically refresh a div every 10 seconds. Currently, my Ajax function looks like this: <script t ...

"Encountering an issue with the parameter 'undefined' in the .find()

Recently, I've been facing some challenges while using the .find() method within a vuex getter. I initialized a store with a list under state (pages) // state.js const state = { pages: [{id:1, content:"Page 1"}, {id:2, content:"Page 2"}] }; In my ...

Issue with background/hero video not adjusting its size

I've been experimenting with creating a page that features a video as the background, but no matter what I try, the video never seems to resize properly. The image below shows how it looks: image in question body { margin: 0; } .hero-se ...

Challenges with border-color and CSS input:focus

The dilemma Currently, I am immersed in a project focusing on constructing a front end using bootstrap4. In order to align with the company's main color scheme, I decided to alter the highlighting color of inputs. To achieve this, I made the followi ...

Having trouble adjusting the space between the footer and the bottom of the page

Looking to create a footer using multiple elements The first element should be positioned at: left: 944px; top: 9749px; The second element should be positioned at: left: 715px; top: 9819px; The third element should be positioned at: left: 718px; top: ...

Updates to props values are not being reflected in the React js application running on the webpack

I keep facing an issue where I have to restart the webpack server every time I try to pass or update props values from parent to child components. It's frustrating that the props values are not updating even after saving the file. Take a look at my p ...

Real-time Email Validation: Instant feedback on email validity, shown at random intervals and does not persist

I am attempting to show the email entered in the email input field in a validation message. The input field also checks my database for registered emails and displays a message based on the outcome. I then included this code from a source. What happens is ...

Issues with Ul List Alignment (CSS and HTML)

<div class="companies"> <ul class="logos"> <li><img src="images/image1.png" alt="" height="25px" /></li> <li><img src="images/image2.png" alt="" height="25px" /></li> <li> ...

What steps do I need to take to retrieve the passed slug in my API (slug=${params.slug})?

Is there a way for me to retrieve the passed slug in my API (slug=${params.slug}) while using the vercel AI SDK? const { messages, input, handleInputChange, handleSubmit, isLoading, error } = useChat({ api: `/api/conversation?slug=${params.slug ...

A more effective strategy for avoiding the use of directives or jQuery in AngularJS

I need guidance on using Angular directives, especially when deciding between JQuery and Angular 1 directives for a particular scenario. Here is an example of my object list: [ { "id":"sdf34fsf345gdfg", "name":"samson", "phone":"9876543210", ...

Choose an element based on its position in the index (multiple elements with the same class)

Can you use Javascript or jQuery to select an element by its index? For example: <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> If I have 4 elements with ...

How do I use onclick to hide a <div> and reveal the content beneath it?

Is there a way for me to hide this <div> when the user clicks outside of it? I want the content behind it to be visible once the <div> is hidden. <html> <style> .overlay { position: fixed; top: 0; left: 0; height: ...

Adding a Fictitious Pair to a JavaScript Object Literal

When I work with object literals in JavaScript, I often encounter syntax errors when adding a new label / value pair without including the trailing comma. This can be frustrating as it's easy to forget to include the necessary delimiter. .draggable({ ...

Angular file upload component with customizable file size limits

I'm currently developing an upload file feature that will transmit the file via nodejs. However, I am encountering an issue related to file size. Whenever the file exceeds a few kilobytes, I encounter the following error: Error: request entity too la ...

How can JavaScript allow access to files outside of a web server environment? Could .htaccess provide a

Currently, I'm facing a challenge with my local server on Mac 10.8. I am trying to serve files such as videos and images from an external hard drive. The path for the external hard drive is HD: /Volumes/ while the web server's path is /Library/Se ...

Interacting with blog posts through comments on both Facebook and the blog's official page on the social media

I'm currently working on a PHP blog and I am looking to integrate Facebook comments into each blog post. My goal is for these comments to be visible both on the website and on its corresponding Facebook page, allowing users from different platforms to ...