JavaScript Event Listener not Working Properly

I've been attempting to implement a feature on my website where the header hides when scrolling down and re-appears when scrolling up. However, I'm struggling to make use of the code snippet below to achieve this functionality. Despite my thorough search for a solution, I haven't been able to figure it out yet. Any assistance would be greatly appreciated, especially considering my beginner level in this area. :)

window.addEventListener('scroll', throttle(throttleTimeout, function() {
        //...
        if (wScrollCurrent <= 0) // scrolled to the very top; element sticks to the top
          removeElementClass(element, elClassHidden);

        else if (wScrollDiff > 0 && hasElementClass(element, elClassHidden)) // scrolled up; element slides in
          removeElementClass(element, elClassHidden);

        else if (wScrollDiff < 0) // scrolled down
        {
          if (wScrollCurrent + wHeight >= dHeight && hasElementClass(element, elClassHidden)) // scrolled to the very bottom; element slides in
            removeElementClass(element, elClassHidden);

          else // scrolled down; element slides out
            addElementClass(element, elClassHidden);
        }
        //...
      }));
.header {
  width: 100%;
  height: 75px;
  position: fixed;
  z-index: 1000;
  background-color: Gray;
  top: 0;
  left: 0;
  -webkit-transition-duration: .5s;
  transition-duration: .5s;
  -webkit-transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  -webkit-transition-property: -webkit-transform;
  transition-property: transform;
}
.header--hidden {
  -webkit-transform: translateY(-100%);
  -ms-transform: translateY(-100%);
  transform: translateY(-100%);
}
    <header class="header" role="banner">
      <div id=Image>
        <a href="http://localhost/lab/">
          <img src="http://localhost/lab/includes/images/logo-small.png">
        </a>
      </div>

      <div id="menu">



        <ul id="menu">
          <li><a href="http://localhost/lab">Home</a>
          </li>

          <li><a href="http://localhost/lab/projects">Projects</a>
          </li>
          <li><a href="http://localhost/lab/videos">Videos</a>
          </li>
          <li><a href="http://localhost/lab/contact">Contact</a>
          </li>
          <li><a href="http://localhost/lab/about">About</a>
          </li>
        </ul>


      </div>
    </header>

Check out the original source of this code.

Answer №1

It's unclear what purpose the site you mentioned serves, as they do not provide the entire code. If you visit their demo page and view the source, you will find the complete listener code like this:

( function ( document, window, index )
    {

    'use strict';

    var elSelector  = '.header',
        element     = document.querySelector( elSelector );

    if( !element ) return true;

    var elHeight        = 0,
        elTop           = 0,
        dHeight         = 0,
        wHeight         = 0,
        wScrollCurrent  = 0,
        wScrollBefore   = 0,
        wScrollDiff     = 0;

    window.addEventListener( 'scroll', function()
    {
        elHeight        = element.offsetHeight;
        dHeight         = document.body.offsetHeight;
        wHeight         = window.innerHeight;
        wScrollCurrent  = window.pageYOffset;
        wScrollDiff     = wScrollBefore - wScrollCurrent;
        elTop           = parseInt( window.getComputedStyle( element ).getPropertyValue( 'top' ) ) + wScrollDiff;

        if( wScrollCurrent <= 0 ) // scrolled to the very top; element sticks to the top
            element.style.top = '0px';

        else if( wScrollDiff > 0 ) // scrolled up; element slides in
            element.style.top = ( elTop > 0 ? 0 : elTop ) + 'px';

        else if( wScrollDiff < 0 ) // scrolled down
        {
            if( wScrollCurrent + wHeight >= dHeight - elHeight )  // scrolled to the very bottom; element slides in
                element.style.top = ( ( elTop = wScrollCurrent + wHeight - dHeight ) < 0 ? elTop : 0 ) + 'px';

            else // scrolled down; element slides out
                element.style.top = ( Math.abs( elTop ) > elHeight ? -elHeight : elTop ) + 'px';
        }

        wScrollBefore = wScrollCurrent;
    });

}( document, window, 0 ));

I cannot guarantee that this will completely resolve the issue, as there may be other areas where incomplete code was provided.

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

Tips for creating a POST request using mongoose in NextJS version 13.4

Currently, I am faced with the challenge of executing a POST request using mongoose in NextJS. In my project structure, I have three key files: lib/dbConnect.js, models/User.js, and app/new/route.ts. As defined, app/new/route.ts is responsible for handling ...

The successful execution of one promise determines the outcome of the $q.all promise

I am currently dealing with a situation where I have three nested promises that I need to refactor into a single $q.all call. The current structure of the code looks like this: ds.saveData(data).then(function (result1){ someOtherVar = result1.Id; ...

Tips for implementing orderBy and filter in ng-repeat when working with an object instead of an array

I am facing a data structure that looks like this: $scope.people = { "ID123": { name_de: "Andre", name_en: "Anrew", age: 30, description: "He is the father of xyz and . . .", . . . ...

Step-by-step guide on integrating node.js and MySQL to store data from an online form in a database

Currently, I am attempting to insert data into a MySQL database using node.js by clicking the submit button. However, an error message has appeared and despite understanding it somewhat, I am unsure of how to proceed. Any assistance would be greatly apprec ...

Setting the column width and border-top in Highcharts

Hey there, I'm facing an issue with my highcharts diagram. 1) Can anyone help me adjust the column width to match the width of the month area? (I've tried changing "width" in CSS but it's not working) 2) Also, how can I remove all borders ...

Why isn't jQuery working properly for showing/hiding elements?

I am attempting to create a functionality where the string remove field can be toggled to show or hide using a single button, depending on its current state. Initially, it should be hidden (using the hidden HTML attribute), and upon clicking the button, it ...

The width of DIVs in Mac Safari exceeds that of other browsers

Encountering an issue that is specific to MAC Safari. Here's the code snippet: <div class="wrapper" style="max-width:1220px"> <div style="width:50%;display:inline-block">First</div> <div style="width:25%;display:inline-block"&g ...

Determine the vertical dimension of an element through a JavaScript event listener

I've been working on creating an Apple-style image sequence scroller from a codepen demo. Here's the link to the original: https://codepen.io/jasprit-singh/pen/LYxzQjB My goal is to modify the JavaScript so that the scroll height is based on a p ...

The button's onclick function is not triggering with just one click

I am having trouble with a JavaScript function not being called on the first click. I have to click the button multiple times for it to execute. Here are the methods I have attempted so far: <a href="javascript:delete_todo(4);void(0)"><img border ...

html table displaying incorrect data while using dynamic data in vue 3

example status 1 Hello there! I'm trying to create a table (check out example status 1 for guidance). Here's the code snippet I am using: <table> <tr> <th>Product</th> <th>Price</th> <th>Av ...

What is causing the gap to appear between the image and the div element underneath?

I recently encountered an issue where I set up an image to scale to full width, but it was always cut off at the bottom when it extended too high. Here is my current setup: div, img, body { margin: 0; padding: 0; } #image { width: 100%; he ...

Break down React website into distinct modules and bundle them as npm dependencies within a single package

Currently, I am developing a React website that includes distinct sections such as contact management and message management. Each of these sections is quite extensive. To navigate to these sections, we use a single dashboard for control. Since separate ...

"Unable to locate the specified file or directory" error message pops up while attempting to save a file

Currently, I am in the process of generating a JSON file using my website with intentions to deploy it later. Below is the code snippet that I have implemented: saveFile = (i, data) => { var filename = `${i}_may.json`; var folder_list = ["desktop", ...

The Bootstrap Navbar fails to function properly when viewed on mobile devices

As a newcomer to BOOTSTRAP 5 and web development in general, I am currently working on creating a simple website using it. I have added a navigation bar, but when I switch my browser to mobile mode, the dropdown menu doesn't work properly and all the ...

Utilizing emotion with MUI v5 for dynamic theming

After upgrading MUI from v4 to v5, I'm facing some difficulties grasping the concept of theming with the various solutions available. I find it challenging to determine when to use MUI theming/styling components and when to opt for emotion ones. Whil ...

JavaScript code may fail to load on initial page load

My JavaScript function utilizes ajax and is triggered when a button is clicked. Oddly, the function works perfectly if you visit the page for a second time, but fails to work on the first visit. I've attempted to include window.onload, document.onlo ...

Decapitalizing URL string in jQuery GET request

Check out my code below: $.get('top secret url and stuff',function(data){ console.log($("[style='color:white']", data.results_html)[0].innerHTML); window.html = document.createElement('d ...

Unable to locate property 'location' due to being undefined

When trying to use the react-router-dom 4.0.0 library, an error was encountered: Uncaught TypeError: Cannot read property 'location' of undefined The issue seems to be with browserHistory. Previously, I had been using react-router 2.x.x witho ...

Generate a novel item by organizing the key of an array of objects

I have an array of objects containing various items: [ { CATEGORY:"Fruits" ITEM_AVAIL:true ITEM_NAME:"Apple" ITEM_PRICE:100 ITEM_UNIT:"per_kg" ITEM_UPDATED:Object ORDER_COUNT:0 }, { CATEG ...

Conduct a unit test to verify that a function successfully connects to an API and accurately stores the retrieved data in a variable

Currently, I am working on creating a unit test for my writing and JavaScript code. This area is still challenging for me, so I am in the process of learning how to do it correctly. The specific function I am focusing on makes an API call and then assigns ...