Improving the performance of Javascript

Currently, I am developing an application with six similar sections on the homepage. Although the app is functional, I find myself duplicating the following block of code:

The only variations between each section are the IDs: #grid and #close, as these IDs differ in each of the six sections.

I attempted to streamline this process by using the following lines:

var $grid = $( '#grid4', '#grid2', '#grid3' ..... ),

and

$close = $( '#close', '#close2', '#close3', .....),

However, this approach led to issues such as sections not loading correctly in the browser.

Below is the repeated block of code:

$(function() {

    var $grid = $( '#grid' ),
      $name = $( '.name' ),
      $close = $( '#close' ),
      $loader = $( '<div class="loader"><i></i><i></i><i></i><i></i><i></i><i></i><span>Loading...</span></div>' ).insertBefore( $grid ),
      stapel = $grid.stapel( {
        onLoad : function() {
          $loader.remove();
        },
        onBeforeOpen : function( pileName ) {
          $name.html( pileName );
        },
        onAfterOpen : function( pileName ) {
          $close.show();
        }
      } );

    $close.on( 'click', function() {
      $close.hide();
      $name.empty();
      stapel.closePile();
    } );

} );

I am seeking ways to enhance the code so that I can avoid repeating the same block while still maintaining distinct IDs for each section to ensure independent behavior. How can I achieve this without redundancy?

Answer №1

If you want to apply the same styling to multiple elements, use the class attribute instead of id.

$grid = $( '.grid'),

For example,

$close = $( '.close')

Your HTML structure should look like this:

<div class="grid">
    <!-- your html -->
    <div class="close">Close</div>
</div>

In this case, the close element is a child of the grid class. You can select and manipulate it using the find() method.

Answer №2

When working with jQuery, you have the option to utilize multiple selectors.

Incorporate multiple elements by selecting them together like so: var $grid = $( '#grid4, #grid2, #grid3' ..... )

Answer №3

Utilizing variables in selectors is a powerful technique

 for (let i=0; i<6; i++) {
     $('#grid' + i).....
     // resulting in #grid0, #grid1, #grid2, etc
 }

Answer №4

Iterate over an array by creating a loop.

var elements = ["#element1", "#element2", "#element3"];
for (var j = 0; j < elements.length; j++) {
    //Insert your code here
}

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

HTML unable to render JSON data

My goal is to showcase a JSON outcome on my HTML page in the following format: { "error": false, "gal_providers": [ { "GalProvider": { "id": "132", "uid": "gp_522f1e047329f", "use ...

Retrieve data from a JSON object and incorporate jQuery autocomplete functionality

Extract the values from the ajax response in JSON object format and utilize jQuery autocomplete to create an autocomplete box. { "consignmentList" : [ "" , "AAA" , "ABC" , "BHU" , "MAN" , "WER" , "ZXC"]} $(document).ready(function() { $("input#autoT ...

Conceal the navigation bar when scrolling to the top of the

Hey there! I'm looking for a way to hide my navigation bar when not scrolling, and then display it again once I start scrolling. Currently, I have two menus on this website: one with a white background and the other with a blue background. You can fi ...

Create a responsive Flexslider with a dynamic background image

Has anyone experienced issues with creating a responsive design while working with flexslider and background images? I tried placing contents inside li tags with background images, but it seems to break the slider's responsiveness. Here is the code sn ...

What is the best way to ensure that child components are "ready" before proceeding with React hooks?

I have a component called Page, which contains multiple instances of the Column component, each with its own user-specific markup. Within the Page component, I need to perform additional actions (such as checking for column overflow and adjusting content ...

Formulate a CANNON entity utilizing the THREE.Mesh technique

I have a THREE.js plane where the points are manipulated using Perlin noise to create terrain. I now need to implement physics for the camera to prevent it from falling through the plane. My goal is to develop a function that can extract the vertices and ...

Guide on capturing an image of a specific div using JavaScript

Currently working on an interactive "HTML Quiz" that operates solely on JavaScript - it's pretty impressive! Upon completion, a results box will appear displaying time taken, percentage score, and number of correct answers out of 10. I envision addin ...

Images in assets folder are not showing up in Vue Bootstrap

I'm attempting to showcase an image similar to the example provided in this guide Below is the code I am using: <template> <b-container fluid class="p-4 bg-dark"> <b-row> <b-col> <b-img rounded="ci ...

Show XML information on an HTML webpage

What is the most effective and straightforward way to pull information from an XML file and showcase it on an HTML page? ...

Bootstrap form validation issues

Currently, I am utilizing Vue.js along with Bootstrap for the creation of a website. In this process, I have set up a form on which I am implementing my custom validation logic. Everything seems to be functioning correctly until the moment when the user hi ...

What are the steps to create a Node.js application and publish it on a local LAN without using Nodemon?

When working on a Node.js application, I often use the following commands to build and serve it locally: //package.json "build": "react-scripts build", To serve it on my local LAN, I typically use: serve -s build However, I have been wondering how I ...

Combining and removing identical values in JavaScript

I need to sum the price values for duplicated elements in an array. Here is the current array: var products = [["product_1", 6, "hamburger"],["product_2", 10, "cola"],["product_2", 7, "cola"], ["product1", 4, "hamburger"]] This is what I am aiming for: ...

Do promises within an array begin execution only when they are passed to Promise.all()?

When an array of promises is built and then passed to the Promise.all method, does execution start immediately or only once Promise.all is called? Consider the following code snippet: let promises: Promise<string> [] = [this.methodCall(), this.meth ...

The text should be wrapped to overlap with an image positioned above it

Currently, I am in the process of enhancing a webpage that contains a significant amount of old legacy code. One issue I have encountered pertains to text wrapping within a fixed-height and width container, as illustrated in the image below: https://i.sst ...

Is there a Polar transformation available in CSS3?

Converting a line into a ring is a straightforward process in graphic design software like GIMP: https://i.sstatic.net/7lQZe.png (source: adamhaskell.net) I'm exploring the possibility of achieving the same effect using CSS. Here's what I&ap ...

Dropdownmenu without borders

I'm having an issue with the dropdown menu on my website - there are no borders showing. I've tried fixing it myself with no luck, so I could really use some help. As a beginner in web development, I don't have much knowledge about these thi ...

Creating Bootstrap 4 forms with full-width input fields within an inline form layout

In my observation, there is a noticeable variance in the behavior of in-line forms between the older version of Bootstrap, v3, and the newer version, V4. I have included two code snippets below: Bootstrap 3 In Bootstrap 3, when the page width decreases, ...

If the item is currently in the array of strings, remove it; otherwise, add it (according to M

Here is the mongoose schema I am working with: const userSchema = new mongoose.Schema({ username: String, password: String, solved: [{type: String}] }) I am attempting to achieve a specific functionality where if a query is present in the "sol ...

What is the best way to update the style following the mapping of an array with JavaScript?

I want to update the color of the element "tr.amount" to green if it is greater than 0. Although I attempted to implement this feature using the code below, I encountered an error: Uncaught TypeError: Cannot set properties of undefined (setting 'colo ...

Exploring the possibilities of integrating jQuery into Firefox extensions

Can someone provide guidance on effectively implementing jQuery within a Firefox extension? My research has not yielded any up-to-date methods that address the latest version of jQuery, and I am aware that directly including it via script tag may lead to c ...