Trouble with jQuery's css() function within an if statement

I'm facing an issue with an if statement in jQuery that is supposed to resize images displayed in the DOM. The logic seems correct as it alerts the new width value, but for some reason, this value isn't being applied to the CSS line below. Any thoughts on what might be causing this problem?

Here's a snippet of the jQuery code:

$('span.i_contact').each(function() {    
    var imgWidth = parseInt($(this).data('image-width'));    
    console.log(imgWidth)
    if (imgWidth < 600) {
        var newWidth = ((imgWidth / 600) * 300);  
        alert(newWidth);
        $(this).css({
            "width":newWidth
        });    
    }    
    // Additional logic here...
});

$("span.o_contact").each(function() {        
    var imgWidth = parseInt($(this).data('image-width'));
    console.log(imgWidth)
    if (imgWidth < 600) {
        var newWidth = ((imgWidth / 600) * 300);
        alert(newWidth);
        $(this).css({
            "width":newWidth
        });    
    }    
    // Additional logic here...
});

This is how the images are generated using ERB:

<% n = steps.index(step) %>
<h2 style="margin-left:20px;"> Step <%= n + 1%></h2>
// More ERB code here...

Answer №1

When using jQuery, the .each function is targeting the span element, so you must navigate through the DOM to access the image within it.

Since it seems that the image is located immediately after the span, utilizing the .next method would be suitable (though there are other approaches available):

$('span.i_contact').each(function() {    
    var imgWidth = parseInt($(this).data('image-width'));    
    console.log(imgWidth);
    if (imgWidth < 600) {
        var newWidth = ((imgWidth / 600) * 300);  
        alert(newWidth);
        $(this).next().css({
            "width":newWidth
        });    
    }   
...

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 to perfectly align columns using Bootstrap

Looking to create two fixed columns in Bootstrap. The current layout can be seen in the image below: https://i.sstatic.net/w41sD.png I want the left and right column to align at the top regardless of the number of items in each column. Refer to the image ...

When the "x" close icon is clicked, the arrow should toggle back to 0 degrees

I've been tackling the challenge of creating an accordion and I'm almost there. However, I'm facing an issue where the arrow doesn't return to its original position after clicking the close "x" icon. The toggle works fine but the arrow ...

Unable to relocate CSS Loader Container

Can someone help me with adjusting the placement of my container? I'm struggling to maintain the styles while getting rid of the position: absolute; on the .dot class. Every attempt I make is resulting in the dots moving erratically! To clarify, I w ...

Monitor modifications to an <input type="text"> element as its value is updated dynamically through JQuery from the server side

I am struggling with detecting when the value of an input field changes after it has been set by clicking a button. I have tried various events but can't seem to find the right one. <!DOCTYPE html> <html> <head> <script src=" ...

What is the best way to access the current scope's DOM element within an AngularJS controller?

In my scenario, I have a collection of outerItems each containing a list of innerItems that are dynamically sorted. Whenever the mouse hovers over an innerItem, I need to display a popup window directly above that specific element. To achieve this, I hav ...

The fetching of data with getJSON through an IP address is experiencing technical

Here's the issue I'm facing: Whenever I make a json call using the code below var url="http://localhost:9000/json"; $.getJSON(url, function(data){ alert(data['yay']); }); It works perfectly fine. However, my localhost IP is ...

Center text in the v-text-field label

Greetings! I've attempted various methods to center the label in my v-text-field, but unfortunately none of them have been successful. Please see the code snippet below: HTML Code <v-text-field dark class="centered-input" label="your code">< ...

Utilizing ellipses within a list item to create a visually appealing design

I've been struggling with this problem for hours, but I can't seem to find a solution. How can I ensure that the text in a list item respects the size of its parent container and uses an ellipsis when necessary? Here's the scenario: <?P ...

Tallying the number of nested documents in a Mongoid collection

In my Rails + Mongoid setup, I have configured 3 models as shown below: # sheet.rb class Sheet include Mongoid::Document field :name, type: String embeds_many :rows end # row.rb class Row include Mongoid::Document field :name, type: String ...

The Jquery Index() method often results in a return value of -

I have developed a function in JavaScript that creates HTML content. Within the test(test1) function, I am checking if test1.Test__c is null and changing the color accordingly. The line ".table-striped > tbody > tr.testcss" is responsible for changin ...

CSS problem causing minor cross-browser compatibility issue

Can anyone assist me in resolving this cross-browser CSS issue? The "get connected" section appears correctly in Firefox, but not in other browsers. Any help is appreciated. Affected HTML <div style="font-size:14px; width:1000px;" id="yjsg3"> ...

Switching the background image with a single click and reverting it back with a double click using jquery

I am working on a project with multiple div elements which need their background images to change upon clicking and revert back to the original image when clicked again. Below is the CSS code for one of the divs, including its Class and ID: .tab_box { wid ...

JavaScript offers a variety of options for creating a link-styled button

Is there a distinction between <a href="javascript:;"></a> and <a href="javascript:void(0);"></a> ? I am looking to create a link-styled button that triggers a JavaScript function when clicked, so I implement the following: ...

Retrieve the number of days, hours, and minutes from a given

Is it possible to use JavaScript (jQuery) to calculate the number of days, hours, and minutes left before a specific future date? For example, if I have a timestamp of 1457136000000, how can I determine the amount of time remaining in terms of days, hours ...

Using Django to make an AJAX call on a Bootstrap dropdown menu

Issue: I'm struggling to find a solution to load the entire chart HTML into a div by calling a function from views.py and passing the context to reference_page.html without having to refresh the page. I have a chart similar to a stock chart, with a d ...

Tips for layering one div on top of another div

I'm looking for guidance on how to position my button divs over my Trapezoids in an overlay fashion. Currently, I have set up an array to store the colors and utilizing the map function to match each button with its corresponding color type. When a ...

Parsing Json data efficiently by utilizing nested loops

I have 2 different collections of JSON data, but I'm unsure of how to utilize JavaScript to parse the information. Data from API1 is stored in a variable named response1: [{"placeid":1,"place_name":"arora-square","city":"miami","state":"florida","c ...

Synced Slideshows

Currently experimenting with the Owl Carousel plugin to create multiple synced carousels using their demo at the link below. However, I'm facing a specific issue when dealing with different numbers of small items in each carousel. I've successfu ...

to invoke a jQuery function located on a different webpage

Imagine you have two web pages: hello.html and wow.html. hello.html contains the following script: <script> $(document).ready(function() { $( "#loader" ).load( "wow.html"); }); </script> while wow.html includes this jQuery function: $(fun ...

Formatting tables

Below is the table structure that I have. I attempted to insert empty tds divs in order to achieve the formatting shown in the image, but I have not been successful. Any suggestions or ideas would be greatly appreciated. <table border="0" cellpadding=" ...