Retrieve the width of every image using jQuery

I need to dynamically set the width of each image caption based on the width of its corresponding image in the img-wrap class. The current code is only applying the width from the first image to all captions.

    <div class="img-wrap">
        <img src="http://lorempixel.com/300/100" />
        <div class="img-caption">aa</div>
    </div>
    <div class="img-wrap">
        <img src="http://lorempixel.com/400/100" />
        <div class="img-caption"></div>
    </div>
    <div class="img-wrap">
        <img src="http://lorempixel.com/500/100" />
        <div class="img-caption">cc</div>
    </div>

    <script>
    var imgwidth = 0;
    $('.img-wrap').each(function (index, value) {
        imgwidth = $(this).find('img').width();
        if ($(this).find('.img-caption').text() === '') {} else {
            $(this).css("background-color", "#000");
            $(this).css("color", "#fff");
            $(this).css("width", imgwidth);
        }
    });
    </script>

The goal is to have each img-caption's width match that of its corresponding image. Currently, they are all inheriting the width of the first image. Any insights on how to achieve this specific width assignment would be greatly appreciated!

Answer №2

Prior to determining its width, it's imperative to allow time for the images to load

$('.img-wrap img').on('load', function () {
    var $currentImg = $(this);
    $currentImg.parent().css({
        "background-color": "#000",
        "color": "#fff",
        "width": $currentImg.width()
    });
});

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

Failing to retain hyperlinks with ajax

Currently, I am utilizing ajax to transmit data from a sophisticated custom field wysiwyg editor. Within this setup, the specific div with the class 'bio' is what I'm addressing. The issue arises when the data is retrieved - all the original ...

When comparing `$(this).parent().children(".classname")` with `$(this).parent().find(".classname")`, it is important to note the distinction

Do you notice any distinction between the following? $(this).parent().children(".name") and $(this).parent().find(".name") Both of these functions seem to return the same object. When I execute console.log($(this).parent().children(".name")); and ...

Tips for effectively displaying HTML data from a database on a web browser

Storing html data in a database is a common practice for many web developers. The html data generated by a wysiwyg editor is typically simple and straightforward. Prior to storing the html data in the database, it is essential to run it through HTMLPurif ...

Stop zombie.js from loading exclusively third-party resources

During a test, I am using zombie.js to load a page from a local express server. However, the page contains a script element that makes a call to Google Analytics. I want to prevent this external script from loading while allowing other local scripts to run ...

The modification of Javascript content type occurring following URL Rewrite

I'm currently working on setting up a Reverse Proxy with ARR and URL rewrite in order to achieve the following redirection: Source: http://localhost/test Destination: http://localhost:83/ The goal is for the final URL displayed to be same as the so ...

Is it possible to adjust the display size of a component in Angular using a selector?

Currently, I'm facing an issue with the size of a selector, <component-selector></component-selector>. It seems to be displaying too large and cutting off the right side of the contents. I've attempted the following code: <div sty ...

What is causing the body to be partially hidden on the right side of every mobile device screen?

I'm currently addressing the mobile optimization issues on a website that I've been developing for some time, and I've encountered my first obstacle. When viewing it on an iPad, the body of the site doesn't extend all the way to the rig ...

wiping out a column in Excel spreadsheets with the help of Node.js or its corresponding node modules

I've attempted various approaches without success. Can you provide guidance on deleting and adding columns within an Excel sheet using Node.js? ...

Accessing and displaying all states in $stateProvider using AngularJS and ui-router

Here's a simple question: how can I find all instances of $stateProvider.state in my app.js, which is my AngularJS config file? In the past with ngRoute, I could achieve this by using a similar approach in my .run() block: .run(function ($route) { ...

What is the best way to create an empty grid-template-row that can expand to occupy the remaining space?

Is there a way to design a grid layout with 3 rows that will take up the entire screen, even if some of the rows are empty? Let's say the header and footer are 100px and 50px respectively. The main area should occupy the rest of the screen. .grid ...

Tips for ensuring the list stays perfectly centered within the navigation bar when placed among three images

I have my navigation bar set up with the logo on the far left and two flags for English and Italian on the far right. The issue I'm facing is that the UL element, being a block element, pushes the flags onto the next line. However, I want the UL to be ...

Customize CSS to target the first and last elements in a row using flexbox styling

I am facing a challenge in selecting the last element of the first row and the first element of the last row within a flex container. The setup involves a flex-wrap: wrap; for my flex container where all elements have flex: auto; with different sizes. Thi ...

The performance of CasperJS when used with AngularJS is subpar

If I click on just one button in Casper, everything works perfectly. The code below passes the test. casper.then(function() { this.click('#loginB'); this.fill('#loginEmailField', { 'loginEmail': '<a ...

Guide to Designing a Three-Column Layout Using Only CSS

I'm currently facing an issue with the alignment of the content section on my webpage which consists of three columns. The DIVs are not floating as expected. Below is the code I am using: <div id="content"> <asp:ContentPlaceHolder ID="Ma ...

What could be the reason why the Google Maps API fails to load on Firefox?

I am currently utilizing the v3 version of Google Maps API. While my map functions perfectly in Safari and Chrome, I encountered an issue in Firefox where I received the error message "google.maps.Map is not a constructor." When inspecting 'google.ma ...

Synchronize numerous PouchDB databases with a single CouchDB database

After reading the PouchDB documentation, I learned that sync occurs between a local database and a remote CouchDB database. Currently, I am working on developing a native application that includes a unique local database for each user (multiple databases) ...

Enhance your website with a jQuery date selection tool integrated with an update

After creating a Calendar User control with jQuery Date picker, I encountered an issue. When using this control on a regular web page, all necessary validations - such as not allowing dates greater than the current date - work perfectly. However, when pl ...

Retrieve the part of a displayed element

Presently, I am developing a modal system using React. A button is located in the sidebar and the modal is represented as a div within the body. In the render function of the main component of my application, two components are being rendered: MyModal M ...

Issue with Modal functionality in Internet Explorer 9

Check out the URL of a page that functions properly in Firefox, Chrome, and Safari, but is experiencing issues in IE 9. Upon page load, a modal displays a banner. The modal I am using can be found at Although the script appears to be correct, I have not ...

Guide on displaying products with category filter on the header search in Magento

I am attempting to show category-specific auto suggest results in the header search, form.mini.phtml <form id="search_mini_form" action="<?php echo $catalogSearchHelper->getResultUrl() ?>" method="get"> <select id="se ...