The code is functioning properly on both Codepen and JSFiddle

I encountered an issue where my code for the header to display only when scrolling up worked perfectly in jsfiddle or codepen, but failed when I tried it in my own program. It was puzzling because I copied and pasted the same code into both platforms and it worked fine there. I am perplexed as to what might be missing or where I could have made an error.

HTML

       <body>
        <header class="nav-down">
            <h1>William Chen</h1>

        </header>
        <section class="module parallax parallax-1">
  <div class="container">
    <h1>Hi.</h1>
  </div>
</section>

<section class="module content">
  <div class="container">
    <h2 class="about">Lorem Ipsum Dolor hello</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
  </div>
</section>
...

CSS

@import url('https://fonts.googleapis.com/css?family=Fjalla+One');
@import url('https://fonts.googleapis.com/css?family=Roboto');
@import url('https://fonts.googleapis.com/css?family=Oswald');
@import url('https://fonts.googleapis.com/css?family=Quicksand');

header {
    background: #f5b335;
    height: 80px;
    position: fixed;
    ...
}

.container {
  max-width: 960px;
  margin: 0 auto;
}
...

@media all and (min-width: 960px) {
  section.module.parallax h1 {
    font-size: 160px;
  }
}

JS

// Hide Header on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('header').outerHeight();
...

P.S Make sure you verify your code by copying it multiple times between your documents and online platforms to ensure accuracy.

Answer №1

It appears that the $(window).scroll listener is being added before jQuery is properly initialized. Additionally, the attempt to set navbarHeight relies on jQuery before it has been initialized. To resolve this issue, make sure to enclose any code that depends on jQuery within a jQuery onReady event handler:

// Hide Header on scroll down
var didScroll, navbarHeight;
var lastScrollTop = 0;
var delta = 5;

$().ready(function(){
  navbarHeight = $('header').outerHeight();

  $(window).scroll(function(event){
    didScroll = true;
  });
})

$(window).scroll(function(event){
    didScroll = true;
});

setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
    }
}, 250);

function hasScrolled() {
    var st = $(this).scrollTop();

    // Ensure scroll distance exceeds delta
    if(Math.abs(lastScrollTop - st) <= delta)
        return;

    // Apply .nav-up class when scrolling down past the navbar to hide it
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
        $('header').removeClass('nav-down').addClass('nav-up');
    } else {
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $('header').removeClass('nav-up').addClass('nav-down');
        }
    }

    lastScrollTop = st;
}

This adjustment guarantees that the scroll listener is attached only after jQuery is properly initialized.

Answer №2

To ensure proper functionality, make sure to include your menu.js file after the jquery js script has been called in your code. Here's an example:

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript"  src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<script src="Scripts/menu.js"></script>

It is important for your jQuery to be defined before the menu.js can utilize the jQuery Library effectively.

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

A function utilizing AJAX search is triggered twice by $(window).bind( 'hashchange', function(e)

Currently, I am grappling with an ajax search issue. The ajax function is triggered on the onblur event. Here's a snippet of the code: function search_ajax(sh_val, sh_act) { ....search logic.... window.location.hash = sh_val + '@' + ...

Looking to extract text between specific match groups using regex from an HTML YouTube page? Here's how you can do

Utilizing the power of Screaming Frog to extract keyword data from YouTube videos has its limitations. The software only displays 160 characters of meta information, which means videos with extensive keywords may not fully show up in this tab. Experimenti ...

Carry out numerous commitments across a range of elements

I have a list of objectIds and I want to perform operations on different collections based on each Id. I prefer executing the operations sequentially. var removeOperation = function(objectified){ return Comps.findOne({reviews : objectified}).populate([ ...

Is there a workaround for jQuery serializing hidden form elements that are set to display:none?

I am facing the following issue: I have a form that needs to be serialized, however, I am using JavaScript to alter the appearance of the select fields. This means that the actual select fields are hidden using display:none property. The problem arises as ...

Is the AngularJS application failing to transmit data accurately to Node.js?

I've been grappling with this issue for a few days now and I can't seem to pinpoint the problem. As someone relatively new to the MEAN stack, I might be overlooking something obvious. I followed the boilerplate code from mean.io for both the back ...

The has-error class cannot be applied to certain input elements

I am currently in the process of validating some inputs within a modal: <div id="modal-section" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="m ...

Issue with drag-and-drop feature conflicting with clicking in Highcharts draggable points

I'm currently using Highcharts version 3.0.7 along with the draggable-points module to enable users to drag points within a displayed series. Users should have the ability to drag a point to move it, as well as click on a point to remove it. The iss ...

I encountered an error stating "Module Not Found" while attempting to locate slick-carousel/slick/slick.css. This issue arose while implementing reacy-slick within my Next.js project

While working on my app with Next.js, I wanted to incorporate a carousel like Slick to display images. I followed the official documentation carefully, imported the necessary CSS file, but encountered an error stating "Module Not Found, can't resolve ...

Modify the material of all other models to match the material of the selected model

I've been tinkering with the vertex shader for 3D models, but I'm running into an issue where I can't seem to change all other models' materials to match the selected model's material. Each viewport contains 4 models, and when I se ...

Facing difficulties with the XPATH due to an inability to access specific parts of the HTML code

Currently, I am facing an issue where I need to click on a link using Selenium and Java. When searching for the link using XPath, I am encountering a problem where only white spaces are displayed instead of most of the webpage content. The highlighted link ...

How can JQuery be utilized to extract the information stored in the "value" parameter of a chosen option?

I have a dropdown menu that dynamically populates its options with numbers. Here is the code for that: <select name="TheServices" id="services-selector"> <option value="" disabled selected hidden>Static Select ...

The JQuery.ajax function encountered an unexpected identifier and threw an Uncaught SyntaxError

Hey there, I'm encountering this error and I'm stumped: jQuery.ajax Uncaught SyntaxError: Unexpected identifier I'm attempting to pass some customer information to another file named "pricealarm.php" in the main directory of the FTP-Serve ...

Tips on passing an integer to an HTML page with Express.js routing

I've got this Express code that currently redirects to the views/index.html page. What I need now is to send some integers to index.html when a specific function executes in this code. Any suggestions on the most efficient way to accomplish this? cons ...

Is the scrolling functionality acting strange while using React Three Fiber?

In my React Three Fiber application, I have the following structure: Website Canvas NativeHTMLContent Canvas Website The issue I'm facing is that after scrolling down the entire canvas, the scrollbar resets to the top and starts scrolling from the t ...

Transform a dynamic Maya model into JSON format for seamless integration with Three.js

After creating a Maya model in Maya 2008, I need to convert it to a JSON format for use with three.js. I have experimented with different methods including: 1) Utilizing the threeJsFileTranslator.py Maya plugin provided in the threejs package. 2) Trying ...

Gather information from "div" tag with the class attribute using Python

I am looking to extract specific financial data (referred to as the Key data) that is housed within <div> </div> tags. I then aim to consolidate this extracted information into an excel sheet which already contains additional harvested data. Th ...

Fixing the problem of digest overflow in AngularJS

I've been working on a code to display a random number in my view, but I keep encountering the following error message: Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! It seems to be related to a digest outflow issue, and I&apo ...

Extract the ng-model name from the scope variable in Angular

Is there a way to accomplish this? ng-model="{{att.myModel}}" I have an array called AllSmallText which contains items. I want to create a form using ng-repeat on AllSmallText and set the ng-model value to be myModel, which is one of the item fields. ...

Responsive Alignment of Slanted Edges using CSS

I have been working on creating a responsive diagonal layout with slanted shapes (refer to the image attached). However, I'm facing a challenge with aligning the edges smoothly at different screen sizes, especially when the rows grow and the screen re ...

A comparison of parent and child components

To implement a child-parent component relationship in Angular, first create two JSON files: parent.json and child.json. The parent.json file should contain the following data: "Id":10001, "name":"John" "Id":10002, ...