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

PHP/jQuery search field

I am currently working on creating a search box using php and jquery to retrieve search results from a database. My goal is to have the search query triggered as the user types into the search box, finding data that matches the keywords entered by the user ...

How can I display JSON data as key-value pairs in ReactJS?

Transitioning from JavaScript to React, I've come across some threads that touch on this topic but none quite hit the mark. I have a local JSON file that was created with a Python script, and it looks something like this: [{"hello": 10, "world": 15 ...

Show information upon opening

I am currently working on a project that involves 4 different divs, and I need the content of each div to be displayed based on dropdown selection. I found a code snippet that was close to what I needed, but after trying to adjust it, I haven't been a ...

This error message 'React Native _this2.refs.myinput.focus is not a function' indicates that

When working with React-Native, I encountered a specific issue involving a custom component that extends from TextInput. The code snippet below demonstrates the relevant components: TextBox.js ... render() { return ( <TextInput {...this.props} ...

A single Ajax call exhibiting varied behavior within a .NET framework application

I have encountered an issue with a webform that contains an ajax call. Surprisingly, the ajax call works perfectly fine on a standalone project, but when I integrate the same code into an existing project, it causes the page to refresh. The existing projec ...

What could be causing the invalid hooks error to appear in the console?

I'm completely stumped as to why this error is popping up when I try to use mutations with React Query. Any insights or advice would be greatly appreciated. Note: I'm implementing this within a function component in React, so it's puzzling ...

Enhancing User Interfaces with JQuery UI Widgets and Dynamic AJAX Calls

Currently involved in geolocation and mapping work, I am creating a JQuery widget to ensure that the code is portable for future projects. However, I have hit a roadblock when it comes to making an AJAX request. Below are a couple of methods from my widge ...

What is the reason behind Chrome's automatic scrolling to ensure the clicked element is fully contained?

Recently, I have observed that when performing ajax page updates (specifically appends to a block, like in "Show more comments" scenarios) Chrome seems to automatically scroll in order to keep the clicked element in view. What is causing this behavior? Wh ...

After implementing ajax jQuery with Laravel 10, this page is experiencing technical difficulties

Seeking assistance from experienced individuals in dealing with Ajax jQuery within the context of Laravel. I have encountered a problem that has proven difficult for me to resolve on my own. Sample html code: <li> <a href="" onclick ...

Standardize date formatting in AngularJS

Retrieve the date in the shared format: {{ dateValue | date:{{dateFormat}} }} The following service is provided: app.service('formatting', function() { var format = new Object(); format.dateFormat = 'medium' var ...

Is there a way to showcase all the information in products while also organizing it in the same manner that I have?

I am looking to sort prices while displaying all the properties of products at the same time. DATA INPUT: const products = [ { "index": 0, "isSale": true, "isExclusive": false, "price": "Rs.2000", "productImage": "product-1.jpg", ...

Issue with jquery .click function not triggering after CSS adjustment

In the process of creating a fun game where two players take turns drawing on a grid by clicking <td> elements. Currently, I have implemented the functionality to toggle the background color of a <td> element from black to white and vice versa ...

What is the best way to organize a flatlist for rendering?

I'm struggling with separating some flat-lists into different components. How can I arrange the rendering of the flat-list like the sample form (Picture "Sample UI")? I've tried, but it's not working correctly as it renders flat list A first ...

What is the best way to include and delete several images on a canvas?

Recently, I've started working with canvas in HTML5 and I'm tasked with creating a paint application. One of the features I need to implement is the ability to dynamically add selected images to the canvas as the mouse moves, and then have the fu ...

Tips for showcasing overflowing text in a menu list by rotating the item text

Imagine you have a TextMenuItem component, using MenuItem from the Material-UI library, that is part of a chain consisting of DropDownSearch > SimpleListMenu > FixedSizeList > TextMenuItem. In simple terms, this creates a searchable dropdown element with t ...

jQuery DatePicker Not Displaying Calendar

I've been attempting to implement a date picker in jQuery. I've included the necessary code within the head tag: <link rel="stylesheet" type="text/css" media="screen" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jqu ...

Ways to verify if a firebase timestamp surpasses the present date

Would you help me with comparing a timestamp field with the current date using JavaScript? This is what I have tried so far: // Initialize an empty array to store documents let myDocs = []; // Call the getDocs function and handle the response await getDo ...

Anchor tags created using JQuery will remain on the same page without redirecting

Presented below is the code I have utilized to construct the anchor tag along with its content. $('div#right-slide').html("<a href=\"http://www.XXXXXXXXXXXX.info/limited-specials/\" ><h1 id=\"specials\">Click Here ...

Retrieve the value of a DOM element within the document.ready function

After researching, I discovered a way to make my textArea resize when the page is fully loaded. $(document).ready(function() { // Handler for .ready() called. }); I decided to test it out and inserted the following code into the function: $(document). ...

Javascript for Cordova utilizing WebSocket and incorporating client side certificates

I am looking to establish a secure SSL/TLS connection between my client and server, with only a specific authorized client allowed to connect. To achieve this, I have generated a client certificate using OpenSSL on the server for mutual authorization. The ...