Is there a way to improve the efficiency of this jQuery/JavaScript snippet by rewriting it?

I've attempted at least 25 variations of this code to make it more efficient, but each one seems to cause issues.

In essence, I am assigning different classes to elements in order to trigger a css/keyframes animation when the window width is 1025px or larger.

Additionally, there is another class being added when the width is less than 1024px, which is meant to reveal the element without any animations.

<script type="text/javascript">
    var width = $(window).width();
    if(width >= 1025) {
    $(window).scroll(function() {
        $('#about .image img.flex').each(function() {
            var position = $(this).offset().top;
            var top = $(window).scrollTop();
            if (position < top+600) { $(this).addClass("slideLeft"); }
        });
        // Additional similar blocks for other elements...
    });
} 
else { 
    $('#about .image img.flex').addClass('visible'); 
    // Additional lines for other elements...
    }       
</script>

EDIT

Perhaps it would be better illustrated in this way:

If you have any suggestions on how I can improve the efficiency of this part...

var width = $(window).width();
    if(width >= 1025) {
    $(window).scroll(function() {
    $('#about .image img.flex').each(function() {
        var position = $(this).offset().top;
        var top = $(window).scrollTop();
        if (position < top+600) { $(this).addClass("slideLeft"); }
    });
    // Similar blocks for other element classes...
    });'

Answer №1

If you want to preserve your addClasses, @icicleking's solution seems promising. In order to achieve this, consider iterating over the essential values.

Check out the DEMO for a visual representation.

var width = $(window).width();

// Array of data objects
var data = [
  { el: '#about .image img.flex', plus: 600, newClass: "slideLeft" },
  { el: '#author .image img.flex', plus: 600, newClass: "slideRight" },
  { el: '#feed .blog_01', plus: 600, newClass: "oneUp" },
  { el: '#feed .blog_02', plus: 600, newClass: "twoUp" },
  { el: '#feed .blog_03', plus: 600, newClass: "thrUp" },
  { el: '#feed .more', plus: 1000, newClass: "moreUp" }
];

if(width >= 1025) {
  $(window).scroll(function() {
    // Iterate over the array of data objects
    data.forEach(function(d) {
      // Target the el attribute for more iteration
      $(d.el).each(function() {
        var position = $(this).offset().top;
        var top = $(window).scrollTop();
        
        if (position < (top + d.plus)) {
          // Add the newClass attribute as required
          $(this).addClass(d.newClass); 
        }
      });
    });
  });
} else { 
  data.forEach(function(d) {
    $(d.el).addClass('visible');
  });
}

Answer №2

It's worth noting that directly triggering animations on scroll events may not be the most efficient method for animating content. Many others have delved into this topic extensively. When you mention "efficient", it seems like you are referring to a solution that is more concise and easier to understand.

One alternative approach could look something like the following (apologies for not mirroring your specific classes):

$(window).scroll(function() {
  var top = $(window).scrollTop();
  $('.all, .the, .selectors, .belong, .to, .us').each(function(e) {
    var position = $(this).offset().top;
    if ($(this).hasClass('.all') && position < top+1000) {
      $(this).addClass('.slideThisClass');
    }
    else if($(this).hasClass('.the') && position < top+600) {
      $(this).addClass('.theOtherSlideClass');
    }
    // etc.
  }
}     

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

When attempting to click the "New" button in a lightning datatable to add a new row, an error

Having trouble adding a new row when clicking the New Button in a Lightning Data table. I've created a lightning-button in HTML and called the method in JavaScript. However, when I click the New button, I'm getting an error message saying Undefin ...

Having trouble adjusting the refresh timer based on user focus with setTimeout

For the past few days, I've been utilizing an ajax call to dynamically refresh specific elements of my webapp every 5 seconds. The implementation with setInterval(refreshElements, 5000) worked perfectly fine. However, now I am considering whether the ...

Is it possible to continuously increase the value of a CSS property with each click?

I am trying to implement a feature where the value of an element decreases each time a different element is clicked. Currently, I have the following code: $("#trigger_heritage").click(function () { $(".heritage_content ul").css("margin-left", + -880); ...

Issues encountered when updating MySql Database from WordPress with Error 500, whereas the code functions properly when used outside of WordPress environment

Question: How can I update a MySQL database from within a JavaScript function on a WordPress WooCommerce page using Ajax? I have a working code snippet for updating the database, but when I integrate it into my WordPress page, I encounter a 500 error. To ...

Can we limit the text in a specific cell to one line on a desktop for a responsive table?

I am facing a challenge with making the second cell in my table have a width of 100% while ensuring that the text stays on one line. While the mobile version is functioning correctly, I am struggling to find a solution for the desktop version as the last ...

Booting up a module in AngularJS without using automatic bootstrapping

Here is the structure of my HTML... <body id="main"> {{pageName}} </body> This is how I implement it in JavaScript: angular.module('myApp',[]) .controller('myController', function($scope){ console.log('initial ...

Style the nth child of a particular type in CSS with a unique color scheme

Is there a way to select the nth child of type and apply different colors without assigning IDs because they are dynamically generated in a loop from a template engine? I found some useful information on this topic here: https://www.w3schools.com/cssref/ ...

The nth-child selector fails to function properly with a customized MUI component in CSS

I've created a styled component as shown below: const FormBox = styled(Box)(({ theme }) => ({ width: "47vw", height: "25vh", backgroundColor: theme.palette.grey[100], borderRadius: theme.shape.borderRadius, marginLeft: ...

What is the alternative to using this.$parent.$emit in Vue 3?

Recently, my application has been upgraded to Vue 3. Following the migration, my linter flagged a deprecation error that is documented at this link: . The documentation provides guidance on replacing this.$emit with the mitt library, however, it does not ...

The controller did not receive the necessary jQuery controls

I've been working on incorporating new controls in jQuery into a GET form, but I'm encountering an issue where the values are not being included in the request when I submit the form. I'm beginning to wonder if jQuery is really the best too ...

Is there a way to store div content in a PHP Session?

Just starting to learn php & ajax, so be patient with me. I have a clickable map. When the user clicks on a point, the value is displayed in a div. Once they select a point, they should be able to proceed to the next step. Now I want to save the content ...

After the completion of the AJAX request, navigate to the bottom of the specified

I have come across a solution on how to scroll to the bottom of a div here. However, it seems that it is not working for me, the same goes for autofocus. I suspect the problem lies in the fact that I am making an AJAX call, and it is not functioning prope ...

What is the best way to serialize data from non-form elements and make it easily accessible through params[:model]?

I have developed a unique Sinatra application that leverages an external API to load data and exhibit it on a page. Utilizing Sinatra, the information is retrieved and stored in a temporary model instance (which is NOT saved) for seamless access to all its ...

A highly effective method for nesting items within a list through recursive functions

I am currently in the process of developing my own commenting system because I have found that existing platforms like Disqus do not meet my specific needs. My backend is built using NodeJS and MongoDB, and I need to execute two primary queries on my data ...

What is the best way to limit the date picker to only accept numbers and hyphens in the input field while blocking any other input in Vue?

I have been utilizing the vue2-datepicker npm package for handling dates. The date input currently accepts all alphabets, numbers, and special characters but I only want it to allow numbers, hyphens, and forward slashes. It's simple to achieve this us ...

How can I use jQuery to transform a div with its elements into a canvas?

Looking for a way to convert a HTML Div and its elements to canvas, and then the canvas to an image using Jquery. I've checked out a website that only converts the whole HTML page, but I need a solution for converting specific Div elements. Any help w ...

Using HTML: The trick to obtaining selection offsets in relation to HTML tags

Let's say I have HTML code like this: <div> <p> start<span>span</span>end </p> </div> I am looking for a way to retrieve the offsets when text is selected, while still taking into account the presence of span ...

Responsive text area with Django and Bootstrap

I created a small JavaScript script to ensure that a text area adjusts responsively based on the size of the accompanying image. It generally works well, but there is a strange random bug that I can't quite figure out. This is how the page should be d ...

What is the best way to change a Buffer array into hexadecimal format?

After making a call to one of my API endpoints, I am receiving a Buffer array in a JSON object. My goal is to convert this array into a more user-friendly format such as hex so that I can easily compare them. Below is a snippet of the current object struct ...

Execute individual queries in MySQL with one single connection

I have implemented functionality that toggles a material icon on/off. When the icon is turned off, I need to execute a delete query. When the icon is turned on, I need to execute an insert query. While I understand the use of AJAX, I am fairly new to it. ...