implement a jQuery loop to dynamically apply css styles

Attempting to utilize a jQuery loop to set a variable that will vary in each iteration through the loop. The plan is for this variable to be assigned to a css property. However, the issue arises where every css property containing the variable ends up with the same value (which ultimately reflects the value at the end of the loop).


pageArray = new Array('web1','web2','web3','web4');
leftTabHeight = 0;
for (var p=0; p<pageArray.length; p++){
    leftTabHeight = parseFloat(p) *100;
    $('.left.main').addClass('flip_left');
    $('.left.main').css({'width':'482px', 'height':'668px', 'z-index':'11','background':'url("images/snake_tab.png") no-repeat, url("images/book_left_main.png") no-repeat','background-position': '0px '+leftTabHeight+'px, 42px 42px','position':'absolute'});

};

HTML:

<div class="web4 left main">
    <h3 class="left_button">web 4</h3>
<h4>web 4</h4>
<p>Stuff</p>
</div>
<div class="web4 left bind">    
</div>

<div class="web3 left main">
<h3 class="left_button">web 3</h3>
<h4>web 3</h4>
<p>stuff</p>
</div>
<div class="web3 left bind">    
</div>

<div class="web2 left main">
<h3 class="left_button">web 2</h3>
<h4>web 2</h4>
<p>Stuff</p>
</div>
<div class="web2 left bind">    
</div>

<div class="web1 left main">
<h3 class="left_button">web 1</h3>
<h4>web 1</h4>
<p>Stuff</p>
</div> 
<div class="web1 left bind">    
</div>

Each class should ideally have a unique background image position, but currently they all overlap at 300px.

Thank you

After inserting a console.log(leftTabHeight) within the loop, it was observed to print 0, 100, 200, 300. Despite this, only the value 300 is being applied.

Answer №1

Here's a possible solution:

let positionValue = 0;
$('.image_container').each(function(){
  $(this).css('background-position', '0px ' + positionValue + 'px 42px 42px');
  positionValue += 100;
});

This code snippet assumes that the elements requiring this styling have the class "image_container".

Answer №2

After some trial and error, I finally solved the issue. The problem lied in the function looping, which caused it to overwrite all the divs each time. To fix this, I incorporated the third class as a variable in the jQuery selection. Here's the updated code that now works seamlessly:

pageArray = new Array('snake','web_s','web1','web2','web3','web4');
var leftTabHeight = 0;
for (var p in pageArray){
    leftTabHeight = parseFloat(p *100);
    $('.'+pageArray[p]+'.left.main').addClass('flip_left');
    $('.'+pageArray[p]+'.left.main').css({'width':'482px', 'height':'668px', 'z-index':'11','background':'url("images/snake_tab.png") no-repeat, url("images/book_left_main.png") no-repeat','background-position': '0px '+leftTabHeight+'px, 42px 42px','position':'absolute'});
};

Answer №3

The issue lies in the fact that you are targeting all elements with the class ".left.main". Modify those lines to read

$('.'+pageArray[p]+'.left.main').css(...)
and your problem will be resolved.

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

How can you access a sibling of the parent element of the current element in Jquery?

I'm working on an HTML project where I have a select field. Depending on the option selected, I need to update the price field with the corresponding price fetched using Ajax. Additionally, I want to be able to input multiple rows by clicking on the ...

Utilize the Google Maps API to align an SVG symbol with the direction of an aircraft's

I have been struggling to update the rotation of the Google Maps API SVG aircraft symbol to display the correct heading as it moves. Although it initially loads with the correct heading, I can't seem to figure out how to dynamically update it. I' ...

Ways to verify that window.open is being invoked from a React component

In my React component, I have a set of nested components, each with its own checkbox. The state hook rulesToDownload starts as an empty array and dynamically adds or removes IDs based on checkbox selection. Upon clicking the 'download' button, t ...

jQuery does not trigger the error event for a 403 status code when loading a new image src

Currently working on a project that involves implementing a static Google map on a webpage. The challenge I am facing is resizing the map dynamically when the page size changes. In order to achieve this, I have created a function that triggers on page resi ...

jQuery live function is not functioning as anticipated

I am facing issues with ajax requests and simple <input type="submit"/>. I have a practice of loading views within other views, in a modular way, using jQuery's .load(url) function to move from one view to another. The problem arises when I loa ...

Dealing with the 'routes not found' error in a Node.js Express application (troubleshooting)

Attempting to address potential missing router errors in my app.js or router file has been a challenge for me. (various solutions found on Stack Overflow have not provided the correct resolution) The current state of my app.js or router files is functiona ...

I keep encountering a parse error when trying to parse JSON that contains a numerical key

After receiving data in JSON format from a Java application, I encountered a parse error when the key was of type Long: 1: { "CONGESTION": 1, "ANSWER": 7 } However, after changing the key to a String as shown below: "1": { ...

Exploring the Concept of Template Element Recursion in Angular JS 2

In my Angular 2 project, I encountered a situation where I needed to iterate through ngFor based on child elements. My component should be able to render a list based on the input provided. Here is an example of the data structure: [ { name: 'ABC ...

What advantages does incorporating inline CSS offer in comparison to using an external CSS file for background images?

I'm currently debating the best approach to take in this situation. Let's say I have a background image that I want to use on multiple pages, each with a different background image. The pages themselves must be responsive. Would it be better to g ...

How can we delete a specific word from a string if it is found in an

Facing a seemingly simple problem that's proving tricky to solve. I have an array of product names and a sentence. The goal is to remove any product names from the sentence if they appear in it. const products = ["premium t-shirt", "t-shirt", "swea ...

How can the edit feature be implemented in AngularJS?

I am struggling with implementing an edit field in AngularJS. Can someone please help me with this? Here is the code for my CRUD operations: var app = angular.module('myApp', []) app.controller('myCtrl', ['$scope', functio ...

Having trouble with the functionality of the cascading menu?

I am having trouble with a drop-down menu. The first level works fine, but I can't seem to get the second level of the menu to display. Appreciate any help you can offer. Thank you. javascript <script type="text/javascript"> $(document).ready( ...

Troubleshooting issues with JavaScript progress bar functionality

I have implemented a progress bar using HTML5, JavaScript and Ajax to showcase file uploads in PHP. The issue I am facing is that the progress bar is not displaying the progress correctly. In addition to that, the echo statements in the PHP code are no ...

Is it possible to precisely position multiple children in a relative manner?

I am currently developing a custom dropdown menu where I want the parent element to be relatively positioned within the page. The goal is for all the child elements of the dropdown menu (the list items) to appear as if they are part of a select element and ...

Issue: NS_ERROR_FAILURE encountered in Firefox when using getBBox()

Is there a way to use the method getBBox() in SVG to retrieve the width and height of an element? I have included my code below, which works in Chrome but not in Firefox. If anyone has a solution to this issue, please let me know. try { console.log( ...

What could be causing my MongoDB Node.js driver's $lookup aggregation query to not produce the expected results?

In my database, I have two collections: users and roles Each user has an array of roles assigned to them: { _id : 61582a79fd033339c73ee290 roles:[615825966bc7d715021ce8fc, 615825966bc7d715021ce8fd] } The roles are defined as follows: [ { ...

Gradually disappear when scrolling "not fluid" or "jerky"

I recently developed a jQuery code to create a fade-out effect on an overlay while scrolling down. Everything seemed to be working smoothly until I noticed that on certain older PCs, the fade effect appears choppy and inconsistent. Strangely enough, on my ...

Retrieve the most recent information based on the ID from an object by utilizing timestamps within Angular 6

I have an array of objects stored in the 'component' variable component=[{id:1,date:'20-10-2020'},{id:1,date:'13-01-2020'},{id:2,date:'30-03-2020'}] Within this array, there are 2 objects with the same 'id&apos ...

Problem encountered when trying to use the sharp package in NuxtJS

I attempted to implement this code in my Nuxt project, but it encountered an issue during compilation. Within my plugin/sharp.js file: import vue from "vue" import sharp from "sharp" vue.use(sharp) And in my nuxt.config.js file: plugi ...

Ways to include additional parameters in jQuery ajax success and error callbacks

When working with a jQuery AJAX success/error function similar to the following: success: function (data, textStatus, jqXHR) { } error: function (jqxr, errorCode, errorThrown) { } I am wondering if there is a method where I can pass an array of valu ...