What are some techniques for improving the performance of this Javascript function?

I implemented a procedure to change the style of my top navigation bar based on the user's scroll position on the page:

/* Handling changes in the top nav during page scrolling */
window.onscroll = function ()
{
    if ($(window).scrollTop() > 150) // Scrolling is triggered at 150 pixels from the top
    {
        $('.navbar-default').addClass('scrolling');
    }
    else
    {
        $('.navbar-default').removeClass('scrolling');
    }
};

However, I noticed that this approach may not be very efficient as the class of navbar-default is manipulated multiple times compared to the number of times the onscroll event is invoked. Additionally, I needed to update an image in the navigation bar based on the scrolling behavior, which led to further complexity:

/* Handling changes in the top nav and image source during page scroll */
window.onscroll = function ()
{
    if ($(window).scrollTop() > 150) // Scrolling is triggered at 150 pixels from the top
    {
        $('.navbar-default').addClass('scrolling');
        $('.navbar-default .navvar-brand img').attr('src','image1.jpg');
    }
    else
    {
        $('.navbar-default').removeClass('scrolling');
        $('.navbar-default .navvar-brand img').attr('src','image2.jpg');
    }
};

This situation seems overly complicated. How can I refactor this code and get rid of the bad smell in it?

Answer №1

Consider these recommendations:

  • Ensure your curly braces are positioned on the same line as the function to avoid potential issues with automatic semi colon insertion - See Example
  • Implement the use of CSS sprites for images - View Tutorial
  • Utilize toggling classes
  • Use CSS to toggle between images instead of dynamically changing image sources based on the class of nav-default

    // Consider this approach...
    .nav-default {
      background-image: url('spriteimage.jpg');
      background-repeat: no-repeat;
      height: // specify height of first image here;
      background-position: // define position of first image here;
    }
    
    .nav-default.scrolling {
      height: // define height of second image here;
      background-position: // specify position of second image here;
    }
    

For more advanced options:

(Note: I cannot guarantee performance improvement, but you may experiment with these suggestions)

  • Periodically check the scroll bar position at small intervals (e.g., every 100ms) rather than monitoring it constantly and then toggle the class accordingly
  • This method may sacrifice some speed in exchange for enhanced consistency (at most, toggling the class every 100ms)

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

Getting the user's name and country using `auth().createUserWithEmailAndPassword` is a simple process

Hey there fellow developers. I'm fairly new to react native and I'm trying to implement firebase authentication for a project. However, I'm stuck on how to include user name and country when using the standard auth().createUserWithEmailAndPa ...

Categorize JQuery Selectors based on the type of elements they

Is there a way to automatically group results by type when using the .each function in JQuery? Consider the example below: $(selector).each(function () { //do stuff here for each found }); The code above goes through each element individually, but ...

Using jQuery to clear a textarea when a select input is changed

Currently, I am in the process of developing a small text editor that enables users to edit files and create new ones. Here is how I have set up my select menu. <select name="reportname" id="reportname" class="form-control"> <option value="zr ...

Unique: "Unique One-Step Deviation in Date Comparison"

A Little Background Information: I am working with data points that span from the current day to 5 days ahead, in 3-hour intervals (such as 10pm, 1am, 4am, 7am...). My goal is to organize these data points into arrays sorted by date, with each array repre ...

Setting up Material-UI for React in conjunction with Typescript: A step-by-step guide

I've encountered issues while trying to integrate Material UI into my React project that's written in Typescript. Following the tutorial, I began by adding the react-tab-event-plugin. import injectTapEventPlugin from 'react-tap-event-plugi ...

In JavaScript, ensure to directly use the value of a variable when defining an asynchronous function, rather than by reference

Hello there, Let me paint you a picture: for (j = 0; j < btnArr.length; j++) { var btn = document.createElement("button"); btn.addEventListener("click", function() { press(this, j) }, false); div.appendChild(btn); } The issue at hand is t ...

When Firebase authentication signs out users who were previously authenticated, it results in them facing permission denied errors

1) User A visits my website, and A is successfully authenticated and can write to the firebase database through the web browser. 2) User B then visits my site, and after being authenticated, they are able to write to the firebase database via the browser. ...

Having trouble with React list.map not functioning properly while deleting items from local storage?

I'm currently developing a budget tracking application that allows users to input various incomes and expenses. To manage the state of this app, I am utilizing useReducer. Each income and expense is represented as an object, and upon submission by the ...

Dynamic image loading in React with custom properties

I'm facing an issue while trying to display an image using the source stored in this.props.src. The correct name of the image file I want to load, "koolImg", is being output by this.props.src. I have imported the file using: import koolImg from ' ...

Are there any other options similar to PhantomJs that offer support for CSS 3D effects?

I am working on capturing a webpage using NodeJs. My current setup involves using PhantomJs to capture screenshots of the page and ffmpeg to convert them into videos. However, I have encountered an issue where the page contains 3D transform CSS, which is n ...

Captive Portal: The outcome of an AJAX post can be quite unpredictable

We are currently implementing a registration step for desktop users when connecting to a network with a Captive Portal. Mobile users authenticate through a mobile app, so this process is exclusive to desktop. While the registration works smoothly in a regu ...

Express.js: Request body with an undefined base64 encoding

I'm currently working on transforming a table in .xls format to individual rows in .csv format. I came across a helpful library for this task called XLSX My initial step involves encoding the .xls table into base64 format. Next, I'm attempting ...

Running MySQL on Express.js in Linux Mint can be accomplished by following these steps

I previously ran MySQL using XAMPP, do I still need to run the MySQL service? Check out this tutorial -> I am encountering confusion in step #2 Server is running at port 8000 /home/aziz/Desktop/Myprojects/backend/crud_fikri/crud-nodejs-mysql/index.j ...

Steps to create a horizontal animation using CSS3

I have 6 different CSS3 animations that I want to split between going right and left. Can these animations be applied separately or do they all have to be the same direction? Is it also possible to adjust the speed of each animation individually? Here is ...

I keep encountering an error with the Next.js Image component, even though I have properly included the src prop

By passing the src prop to the UserCard component, I am encountering the following error message. Error Unhandled Runtime Error Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` comp ...

Introducing React JSX via a nifty bookmarklet

Looking to convert code found in an HTML file into a bookmarklet? Here's the code snippets involved: <script src="JSXTransformer-0.13.3.js"></script> <script src="react-0.13.3.js"></script> <script type="text/jsx;harmony=tr ...

Having issues with column offsetting in Bootstrap v4.0.0-beta

While using Bootstrap 4 Beta (Bootstrap v4.0.0-beta), I encountered an issue with offsetting columns. Previously, I used offset-md-* and it worked fine. However, this feature has been removed in BS4 Beta as per the documentation. The new method suggested i ...

Scroll up event and sticky header using jQuery

I'm working on a function $(document).ready(function () { var lastScroll = 0; $(window).scroll(function(event){ var st = $(this).scrollTop(); if ((lastScroll - st) == 5) { $("header").css("position", "fixed"); ...

What could be causing the flexbox code to not take effect and the text to refuse wrapping?

I've been utilizing flexbox to style my content, and it worked seamlessly on the first three divs. However, when I attempted to apply the same styling to the fourth one, it didn't quite work out as planned. Despite trying options like flex-wrap t ...

Tips for choosing newly added elements using jQuery selectors

Is there a way to select new elements that are dynamically added to the page and have the rel="tooltip" attribute using jQuery? I have tried using the $("[rel='tooltip']").tooltip(); selector, but it doesn't seem to work when new elements ar ...