Set a div to have a fixed position after scrolling past a specified number of pixels

Currently, I am experimenting with a unique parallax effect on my website.

I would like to change #menu from "position: relative;" to "position: fixed;" after scrolling for the height of the header (approximately 100px).

This is the current version of my code:

<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">

body {
    margin: 0;
}

header {
    position: fixed;
    top: 0;
    width: 100%;
    z-index: -1;
    height: 100px;
    background: green;
}

.wrapper {
    margin-top: 100px;
    margin-bottom: 60px;
}

.content {
    position: relative;
    z-index: 1;
    border-top: 1px solid black;
    border-bottom: 1px solid black; 
    background: white;
    min-height: 1500px;
}

#menu{
    width: 100%;
    height: 50px;
    background-color: red;
    position: relative;
}

footer {
    width: 100%;
    position: fixed;
    z-index: -1;
    bottom: 0;
    background: black;
    color: white;
    height: 60px;
}

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
    $(window).scroll(function(){
        if ($(window).scrollTop() >= $(header).height()) {
             $("#menu").css('position', 'fixed');
             alert("I'm working fine.");
        }
    });
</script>
</head>

<body>
    <div class="wrapper">
        <header id="head">
            <h1>HEADER</h1>
        </header>

        <div class="content">
            <div id="menu">I SHOULD BE FIXED AFTER SCROLLING FOR 100px.</div>
            <h1>CONTENT</h1>
        </div>

        <footer>
            <h1>FOOTER</h1>
        </footer>
    </div>
</body>

</html>

JSFiddle

It seems that the jQuery script is not functioning as expected, and I am unsure why.

Any assistance offered would be greatly valued. Many thanks in advance.

Answer №1

To specify any HTML tag, we can enclose it in either single quotes ('html tag') or double quotes ("html tag").

Therefore, your updated code will appear as follows.

$(window).scroll(function(){
    if ($(window).scrollTop() >= $('header').height()) {
         $("#menu").css('position', 'fixed');
         alert("I'm functioning properly.");
    }
});

Answer №2

After running the script on my website, an error was caught by the console indicating that "header is not defined." To fix this issue, modify the code in as follows:

<script type="text/javascript">
    $(window).scroll(function(){
        if ($(window).scrollTop() >= $('#head').height()) {
             $("#menu").css('position', 'fixed');
             alert("I'm working fine.");
        }
    });
</script>

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

An illustration of Agile Web Development With Rails showcases an image placed on top of text

Currently, I am engrossed in the book Agile Web Development With Rails and have encountered a slight hitch on page 96. Following the instructions meticulously from the book, but unfortunately hitting an obstacle as shown below: https://i.sstatic.net/gp ...

Is it possible to load textures in Three.js and Cordova without relying on a server or HTTP?

I am currently working on developing a Cordova game using Three.js with the goal of making it playable offline. However, I have encountered an issue where Three.js requires texture files to be served via HTTP, making it challenging to achieve offline funct ...

Position a table with a fixed center

Hi everyone, I'm struggling to center a table in a fixed position on a webpage. Can anyone help me figure out how to do this? Here is what I have tried so far... http://pastebin.com/cjAqkyjg ...

Extension with a responsive design - Conceal all columns with the exception of the initial one

I am currently utilizing the latest version of jQuery DataTables along with the Responsive extension. While everything is functioning properly on tablets and desktops, I encounter an issue when the screen size drops below approximately 600px. When the res ...

Verify for a class that does not exist

I am working on a script that updates the content of a div and increments its value by 1 $(function() { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'), }, }); ...

Hovering does not activate the CSS dropdown

I have been struggling to implement a pure CSS menu that shows on hover. Although everything seems to work fine, I encounter an issue when trying to hide and then show the menu again upon hover. Here is the HTML code: <ul id="nav-menu"> <li& ...

Inserting HTML content dynamically using JavaScript

I successfully created a JavaScript function to add an input file tag and a link, but now I would like to include a radio button along with some text next to it. I have been able to add the radio button without any issues, but I'm unsure how to insert ...

Utilize multiple iterations of Bootstrap stylesheets within a single webpage

Incorporating Bootstrap CSS 4.6 globally on all pages is a requirement, however there is one section of a page that necessitates the use of a 3rd party tool utilizing Bootstrap CSS 3.7. Unfortunately, upgrading to version 4.6 causes issues with the functio ...

How about rejuvenating a Div with some PHP magic inside?

My goal is to automatically update a div every x seconds by using the following code: The div only contains a small PHP timezone code. This is the code snippet I am implementing: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/ li ...

Inline-block styling behaving incorrectly within span element

I am facing an issue with aligning a validation message inline with a textbox in my HTML code. Despite trying various options, the validation message appears just below the textbox instead of beside it. Below is the snippet of the code in question: HTML ...

use css to align multiple div elements

I am struggling to line up more than five div tags on the same line. Here is my CSS: <style> #yes { float: left; width: 18%; margin:1px; } </style> Example of HTML code: echo '<div id="yes">'.'<b>'.'Job T ...

Having trouble iterating through a JSON response in an Ember template

Here is the content of my JSON array: { "object": { "assignments": [ { "assignmentId": 14706368, "sectionId": 0, "assignmentTitle": "file attachment A", "assignmentSta ...

In React Native, I must include individual radio buttons for each item retrieved from the API

When I select a radio button on mobile, all radio buttons get selected instead of just the one clicked. Here is the current behavior: https://i.stack.imgur.com/qRJqV.jpg The expected behavior is to have only the clicked radio button selected, like in thi ...

What is the process for binding attributes using v-bind with a one-time binding?

Currently, I am utilizing the vue-i18n library for localization purposes. An issue I have encountered is when attempting to translate input placeholders using the following syntax: <input type="text" v-model="someValue" :placeholder="$t('translati ...

conceal elements using the <option> class隐藏

Although it seems like a simple task, I'm struggling to make it work. I created a form where the user can select a month from a list using the tags: <select> <option> When the selection is changed, the class .gone from the day SELECT is ...

Difficulties involving AJAX requests in Firefox and Internet Explorer

My checkbox triggers an AJAX request whenever its state changes (checked/unchecked). Everything was working fine when I tested in Chrome. But when I tried using Firefox or IE, the AJAX request wasn't updating the value in the SQL server. I'm a b ...

The reason the section's height is set to 0 is due to the absolute positioning of the div

Currently, I have a section tag with three divs inside that are positioned absolute (used for the isotope plugin). <section id="section1" class="cd-section"> // pos. static/relative has height 0px <div class="itemIso"> // pos. absolute, he ...

Utilizing a parent scope variable in a callback function

This question delves more into the concept of JavaScript Closures rather than Firebase. The issue arises in the code snippet below, where the Firebase callback fails to recognize the variable myArr from the outer scope. function show_fb() { var myAr ...

Position the text to the left of the floating paragraph on the right

I am looking to align some text on the right side of the page with consistent starting positions. Each paragraph has two spans, one floated left and the other floated right. Here is an example with HTML and an image included for clarity. .card { ma ...

I can't seem to retrieve my email using the code provided. The second console statement is not displaying any information. Why might this be happening?

I've been struggling to retrieve the email entered in a form and print it in the console. Despite my code compiling without errors, the email is not being fetched. My goal is to utilize nodemailer for sending registration emails, but I'm encounte ...