Implementing a JQuery script that triggers every time there is a change in the scroll

This script creates a shrinking effect on a box followed by a fade-in/out transition when the scroll position changes. However, the issue is that it triggers every time there is a scroll position change. For example, if the scroll position is at 100px and the user scrolls down once more, the text inside li.um would fade in and out unnecessarily. Is there a way to modify the code so it only runs when the scroll position switches from greater than 60 to less than 60, and vice versa?

$(window).bind('scroll', function() {
    var viewportWidth = $(window).width();
     if ($(window).scrollTop() > 60) {
        $("li.um").fadeOut(200);
        $("ul.undermenu").stop(true, false).animate({width:'160px'}, { duration: 500, queue: true});
        $("ul.undermenu").animate({height:'60px'}, { duration: 200, queue: true});
        window.setTimeout(function () {
        $('li.um').html('12345678901 <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="27574253426755524152544a52544e4409444809524c">[email protected]</a>');
        }, 700);
        $("li.um").fadeIn(200);
     }

     else {
         $("li.um").fadeOut(200);
         $("ul.undermenu").stop(true, false).animate({height:'30px'}, { duration: 200, queue: true});
         $("ul.undermenu").animate({width:viewportWidth}, { duration: 500,  queue: true});
         window.setTimeout(function () {
         $('li.um').html('Email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95e5f0e1f0d5e7e0f3e0e6f8e0e6fcf6bbf6fabbe0fe">[email protected]</a> | Call: 12345678901 | Call: 01290923876');
         }, 700);
         $("li.um").fadeIn(200);
     }
});

Fiddle (scroll down a few times to see the fading in/out effect of the text)

Answer №1

In order to effectively trigger the desired action, it is important to maintain awareness of your previous position. Below is a potential approach utilizing the existing code provided:

var lastScrollTop = 0;
$(window).bind('scroll', function() {
    var widthOfViewport = $(window).width(),
        currentScrollTop = $(window).scrollTop();
    if (currentScrollTop > 60) {
       if(lastScrollTop <= 60) {
            $("li.um").fadeOut(200);
            $("ul.undermenu").stop(true, false).animate({width:'160px'}, { duration: 500, queue: true});
            $("ul.undermenu").animate({height:'60px'}, { duration: 200, queue: true});
            window.setTimeout(function () {
                $('li.um').html('12345678901 <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d5d4859486d5f584b585e40585e444e034e42035846">[email protected]</a>');
            }, 700);
            $("li.um").fadeIn(200);
        }
     } else if (lastScrollTop > 60) {
        $("li.um").fadeOut(200);
        $("ul.undermenu").stop(true, false).animate({height:'30px'}, { duration: 200, queue: true});
        $("ul.undermenu").animate({width:widthOfViewport}, { duration: 500,  queue: true});
        window.setTimeout(function () {
            $('li.um').html('Email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9d9ccddcce9dbdccfdcdac4dcdac0ca87cac687dcc2">[email protected]</a> | Call: 12345678901 | Call: 01290923876');
          }, 700);
        $("li.um").fadeIn(200);
     }
     lastScrollTop = currentScrollTop;
});

Answer №2

Here is a helpful tip to enhance your efficiency once more :) To improve your performance, consider implementing a throttle or debounce wrapper function that responds to a unique custom event. Take a look at this example:

/**
 * @description control the frequency of events with the same id, ideal for window resizing, typing keystrokes, etc ...
 * @param {Function} func : callback function to execute upon completion
 * @param {Integer} wait : time delay in milliseconds
 * @param {String} id : identifier for the event
 */
var controlledEvent = (function () {
    var timers = {};

    return function (func, wait, id) {
        wait = wait || 200;
        id = id || 'unspecified';

        if (timers[id]) {
            clearTimeout(timers[id]);
        }

        timers[id] = setTimeout(func, wait);
    };
})();

You can apply it as follows:

controlledEvent(function(){/*your code implementation here*/}, 500, 'my scroll action');

Check out a live demonstration

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 aligning a custom icon to the left in a Jquery mobile header

I have successfully implemented a custom icon in the header, but it is currently displaying in the center. How can I adjust it to be positioned on the left side instead? <div data-role="header" data-theme="a"> <h3> ...

"Encountering issues with calling a Node.js function upon clicking the button

I'm facing an issue with the button I created to call a node.js server function route getMentions, as it's not executing properly. Here is the code for my button in index.html: <button action="/getMentions" class="btn" id="btn1">Show Ment ...

CSS/Jade/HTML: struggling to get boxes to align properly on the same line

I'm currently working with a Jade template that looks like this: extends layout block content h2 Characters and Portraits div(id="portraitsBox") - var portraits = ["Clown-Fox", "Dragon-Bear", "Fish-Bear", "Deer-Wolf", "Salamander-Ant", "Sid ...

An invalid primitive was encountered in the JSON data

I am trying to pass the number of seats to TryJSIN.aspx in my function test(), but I keep encountering errors. When I use type 'GET', I get the following error: "Invalid JSON primitive: 1-9." The value 1-9 represents the number of seats. Howe ...

Fixed width layout in Bootstrap 3 with a footer that spans the full width of the

Currently, I am utilizing Bootstrap 3 with a fixed width set-up. The footer on my site consists of two columns, each with a different background color. In order to ensure that the content in the footer aligns properly with the rest of the website, I want ...

AngularJS is failing to recognize the onload event when loading a URL

I am currently working with the AngularJS Framework and I have encountered an issue. My directive only seems to work when the window is fully loaded. screensCreators.directive('createscreen', function () { return { restrict: "A", ...

Automatically select and pre-fill a list item based on its value using jQuery

I'm a beginner in JQuery. In my application I have the following: Here is my HTML code: <ul id="list"> <li> <a class="selected" value="0" href="#" id="sel">ALL</a> </li> <li> <a hre ...

JavaScript encountered an issue when trying to display HTML content

Through my PHP code, I am attempting to create a popup window that displays the content of an HTML file. However, after adding script tags, no HTML content is displayed. When I tried echoing out $row2, only the word 'array' appeared on the screen ...

The logo image dynamically switches as the user scrolls through various colored sections

Looking to create a feature that changes the logo image as users scroll through different colored sections. Specifically, switching between dark and light themes. a) How can we determine if the section the user is currently on has a dark or light theme? b ...

Adjusting images of various sizes within a single row to fit accordingly

I am faced with a challenge of aligning a set of images on a webpage, each with varying heights, widths, and aspect ratios. My goal is to arrange them in a way that they fit seamlessly across the screen while ensuring their heights are uniform. Adjusting ...

Maintain the style of the main navigation menu when hovering over the sub-navigation items

I am currently in the process of redesigning the navigation bar for a specific website. The site utilizes Bootstrap, with a main navbar and a secondary navbar-subnav. While I have been able to style both navs accordingly, I am encountering difficulties whe ...

Swapping out pages with JSON outcomes is a common practice when utilizing ASP.Net MVC in conjunction with JQuery Ajax

When making an ajax call to update an entity and returning the success state in the MVC controller, I encountered a problem that resulted in the page changing with the URL becoming that of the MVC controller action and displaying the JSON result as content ...

Formatting output for similar values in R can be achieved using various functions and

I need assistance with formatting output using cat or sprintf in R according to the id: Initial Data: a <- "1<--A ,1<--B ,1<--C ,1<--D" b <- "A-->1 ,A-->2 ,A-->3 ,A-->4 ,A-->5 ,A-->6 ,B-->1 ,B-->2,C-->1,C--> ...

Efficient ways to enhance CSS animations (including scaling, rotating, and blurring)

In this HTML example, there are two animated pictures - one background and the other an object. Despite using scale and rotate animations, the performance is choppy on full HD monitors, especially in Firefox where it runs at about 20 fps. Initially, jQuer ...

When the class name is identical, the click event appears to be malfunctioning

Why isn't the click event working in this code? What am I doing wrong? $(document).ready(function() { $('.dashboardList').click(function() { alert("hello"); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1. ...

Using JQuery to modify several background images in unison

I have a CSS code that uses 8 images to create a frame: background-image: url(images/blue/tl.png), url(images/blue/tr.png), url(images/blue/bl.png), url(images/blue/br.png), url(images/blue/t.png),url(images/blue/b.png),url(images/blue/l.png),url(images/b ...

Currently, I am compiling a list of tasks that need to be completed, but I am encountering a dilemma that is proving difficult to resolve

Recently delved into the world of Javascript and encountered a roadblock that I can't seem to overcome. Here's the snippet of code causing me trouble: add = document.getElementById("add"); add.addEventListener("click", () => { console.log("Ple ...

A collapsible select list with checkboxes for children items

I am currently developing a website using Vue.js, HTML, and SCSS. I am looking to implement a drop-down functionality similar to the animated example provided in the gif below: https://i.stack.imgur.com/Mia2D.gif The gif demonstrates how the drop-down me ...

Transferring a variable after a successful jQuery call

I recently posted a similar question on Stack Overflow, but it seems like the responses there disappear quickly and I didn't receive a satisfactory answer. Personally, I find it easier to understand things when they are related directly to my own cod ...

What are some strategies for efficiently positioning buttons using CSS to prevent unwanted consequences?

Below is the CSS and HTML code, detailing a specific issue. * { box-sizing: border-box; font-family: Georgia, 'Times New Roman', Times, serif; } body { margin: 0; font-family: Georgia, 'Times New Roman', Times, serif; } .topn ...