The scroll function is executed only one time

I'm currently working on implementing a sticky sidebar snippet using jQuery. However, I am facing an issue where the function within .scroll() is only executing once instead of on every scroll event. Can anyone help me identify what I might be doing incorrectly?

var sticky = $('#sticky');
var staticSticky = $(sticky).offset().top;

$(window).scroll(moveEl(sticky, staticSticky));

function moveEl(element, staticElToTop){
    if( $(window).scrollTop() >= staticElToTop ){
        $(element).css('top', $(window).scrollTop() + 'px');
    }
}

You can view my current attempt here: http://codepen.io/ExcellentSP/pen/GqZwVG

At this stage, the code provided is not fully operational. My primary objective is to resolve the scroll event functionality before moving forward with further development.

Answer №1

To ensure your moveEl method is properly executed when the window is scrolled, you should wrap its content within a function that is returned for the $(window).scroll() event like so:

var sticky = $('#sticky');
var staticSticky = $(sticky).offset().top;

$(window).scroll(moveEl(sticky, staticSticky));

function moveEl(element, staticElToTop) {
  return function() {
    if( $(window).scrollTop() >= staticElToTop ){
        $(element).css('top', $(window).scrollTop() + 'px');
    }
  }
}

Clarification: The key point here is that by simply calling a function without returning anything, it defaults to undefined, making it equivalent to $(window).scroll(undefined). This explains why the function only runs once initially.

However, by returning a function within the moveEl method, the .scroll() event now has a valid handler attached to it, transforming it into $(window).scroll(handler). Consequently, the function will now act as intended every time the window is scrolled.

Answer №2

By calling $(window).scroll(moveEl(sticky, staticSticky));, you are telling JavaScript to run the function without passing its reference.

 $(window).scroll(function(){ 
   moveEl(sticky, staticSticky);
 });

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

Implementing dual language codes for a single locale in internationalization (i18n) efforts

I am currently using i18n to display translations in English and Japanese. The default language is set to English with the code en, but I have recently discovered that my website is not utilizing the correct ISO language code for Japanese, which should be ...

Ways to conceal a badge using JavaScript

Can anyone help me figure out how to edit the data-count of a badge and hide the badge using JavaScript in a Bootstrap 5 navbar with a stacked Font Awesome icon? I have tried the following: document.getElementsByClassName("p1 fa-stack fa-2x has-badge ...

Disappearance of external page upon refreshing - jquery mobile

I'm in the process of developing a jQuery mobile application that loads external pages into a specified div when a link is clicked. These externally loaded pages contain links to additional pages. However, I've noticed that when I click on these ...

The casperjs evaluate function isn't able to provide me with the necessary data I

Having trouble getting my function to return data correctly. I am trying to retrieve the value of this input box. <input type="text" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b6e736a667b6764646025686466">[em ...

Retrieving Information from API using Vue.js

In the code snippet below, I am displaying data from an API for all flats on a single page. However, I am facing difficulty in showing the floor number for each flat. The JSON body is as follows: { "response": [ { "fl ...

Utilizing jQuery to select an attribute containing a special character

There is a special div with a unique data-id: <div data-id=""> </div> I tried to target this div using jQuery, but it didn't work as expected: jQuery("[data-id='']").text('hello'); Can anyone help me on how to ...

What is the best way to test an externally hosted application with Testacular and AngularJS?

I have a Pyramid app running on http://localhost:6543. This app serves the AngularJS app at /. This app utilizes socket.io. The query is: Can I test this application using these tools? In my scenario.js file, I have the following: beforeEach(function( ...

css issue with focus on ie11

<style type="text/css"> .main { position: absolute; border-radius: 8px; border: none; height: 54%; top: 35%; /*33%*/ color: #FFFFFF; font-size: 0.7em; o ...

Is it possible to verify the authenticity of JSON data retrieved from

I'm currently working on validating JSON input from users and came across a challenge. I've found a way to check if the text a user enters is valid JSON using a simple function, like below: function IsJsonString(str) { try { JSON.par ...

Mongoose/JS - Bypassing all then blocks and breaking out of the code

If I need to check if a certain ID exists and exit the process if an error is encountered right from the beginning, is there a more concise way to do it rather than using an if-else block? For example: Question.find({_id: req.headers['questionid&ap ...

Issue with Setting Value in JQuery Select Box

I am in the process of designing a webpage that allows users to edit listings they have created on my website. These listings fall under three main categories, each with its own set of subcategories. To streamline this process, I am implementing AJAX to dy ...

Retrieve the URL for the React component

I'm facing some challenges with React fundamentals :/ I have a piece of code that creates a table using JSON data: import React from 'react' import { DataTable } from 'react-data-components'; function createTable(data) { ...

Tips for avoiding repeated Modal Popup instances and preventing the page from automatically scrolling to the last element when using ReactJS

I've been working on a project where I'm fetching data from a server and displaying 10 different sets of data in Bootstrap cards using the map() function. Each card contains a button to open a modal, along with a Link that shows the route related ...

Struggling with organizing my code in node.js - it's all over the place and not very reliable. How should I tackle this

Can anyone help me troubleshoot an issue I'm facing with code that writes to the console late or in random order? var request = require('request'); var vFind = 'HelloWorld'; var vFound = false; var vSites = ['http://www.youtu ...

Linking two socket.io clients together (Establishing a direct socket-to-socket connection that works across different browsers)

Can a direct P2P connection be established between two browsers using socket.io-client, bypassing the node.js server they are currently connected to? If possible, how? The goal is for clients A and B to communicate directly without going through the node. ...

Dropdown box not displaying any choices

I developed a basic reusable component in the following way: Typescript (TS) import {Component, Input, OnInit} from '@angular/core'; import {FormControl} from '@angular/forms'; @Component({ selector: 'app-select', templa ...

Node.js is indicating that the certificate has expired

When using Mikeal's request library (https://github.com/mikeal/request) to send an https request to a server, I keep encountering an authorization error of CERT_HAS_EXPIRED. request({ url: 'https://www.domain.com/api/endpoint', ...

Connect my Vue.js model data to the object that will be used for submission

I need help figuring out how to bind data from my input field into my Vue.js model. I've tried putting the UnitName inside the model but it's not working. Can someone provide some guidance on how to achieve this? new Vue({ el: "#app", da ...

Is there a way to implement retry functionality with a delay in RxJs without resorting to the outdated retryWhen method?

I'd like to implement a retry mechanism for an observable chain with a delay of 2 seconds. While researching, I found some solutions using retryWhen. However, it appears that retryWhen is deprecated and I prefer not to use it. The retry with delay s ...

Why are my cursor and my drawing line on opposite sides?

I've been working on a JavaScript drawing app, but I'm facing an issue where the drawn elements are not aligned with my cursor. The positioning seems off, especially when moving to the right or up on the canvas. As I move towards the furthest lef ...