How can you match the width of a series of elements to the width of an image directly preceding the div?

Looking to ensure that a series of captions have the same width as the images preceding them.

This is the HTML code:

<div class="theparent"> 
<img src="pic.jpg"/>
<div class="caption">
        hello
    </div>
<div>
<div class="theparent">
    <img src="pic2.jpg"/>
    <div class="caption">
        hello
   </div>
<div>
<div class="theparent">
<img src="pic3.jpg"/>     
<div class="caption">
        hello
     </div>
<div>

Each image has a different width, but I want each caption to match the width of the previous picture. This width may change over time, requiring the use of SetTimeOut.

I've attempted something like this:

function launchcaption() {
 var myWidth = $(".theparent img").width();
  $(this).next().css( "width", "myWidth" );
}

setTimeout(launchcaption, 10);

Please avoid suggesting CSS solutions, as JavaScript is necessary in this case. Thank you!

Answer №1

The selector is incomplete without the . Make this alteration:

$(this).find("title").css("font-size", newSize);

Change it to:

$(this).find(".title").css("font-size", newSize);

Answer №2

To achieve this effect using css, simply specify that the width of the caption should be 100% by adding the following code:

.caption{
     width: 100%;
}

This will dynamically adjust the width according to its parent element.

Answer №3

How about this:

$(".caption").each(function(){
    $(this).css("width", $(this).prev('img').css("width"));
});

(customize the SetTimeOut logic as per your requirements...)

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 I remove the script from Response.Write?

Instead of using Response.Write to test some values in code with an alert box, I tried writing dynamic javascript directly into the page. Even after reverting the code, rebuilding, and clearing all temp data from IE, the alert still pops up. I followed a ...

Unable to interpret encoded json information

I'm currently developing a basic chat system using PHP and jQuery with Ajax, but I've encountered an issue when trying to display a JSON encoded string through the ajax callback function. Below is the code for the ajax request: $.ajax({ url: ...

Accessing the Bootstrap tab form from an external source

I currently have Bootstrap tabs on a page and they are functioning correctly. However, I am looking to open these tabs from an external page. Is this feasible? <div role="tabpanel"> <ul class="nav nav-tabs" role="tablist"> ...

Implement a personalized click function for the delete icon in the mini cart

Is there a way to customize the click event for the remove button in the mini cart? function ajax_call(){ $.ajax({ url: ajax_url, type: 'post', data: {action : 'remove_from_cart','cart_item_key' : 10}, ...

Guide on populating a Vue.js input field with a value retrieved from a JSON object

Could someone please assist me with a problem I am encountering? I need to extract and display the values from an input form for "name" and "position", but the data is in JSON format. {"id":5,"name":"the name","pos":"the position"} This code snippet repr ...

What is the best way to retrieve an element made in a different function within JavaScript?

I have a main button on the screen and when I click that button, it generates two more buttons. These additional buttons should each have their own functionality and click events, but since they are created within a function without global variables or ids ...

The JSON.parse function encountered an Uncaught SyntaxError due to an unexpected token 'o

I'm struggling with this JSON data: const info = [{ "ID":1,"Name":"Test", "subitem": [ {"idenID":1,"Code":"254630"}, {"idenID":2,"Code":"4566"}, {"idenID":3,"Code":"4566"} ] }]; console.log(JSON.parse(info)); //U ...

Updating user credits through the Model::factory() method is a common practice in my workflow

I need to update the UserCredits after a purchase. For example, if a user currently has 10 credits and purchases 10 more, I want to add the purchased credits to their existing total. The goal is to increment the current credit score with the new credits ...

delivering the user's ID and username from php back to the website

Currently, I am in the process of creating a sign-in feature for my website (index.php): To achieve this, I have designed a form that will submit information to the validation-sign-in.php file for processing: (Encryption will be implemented at a later st ...

The proper way to define an event delegator's syntax

Typically, when you want to handle a button click event, you would do so like this: $(document).ready(function() { $("button").click(function() { doSomething(); }); }); However, in the scenario of an event delegator, you may need to respon ...

Error encountered: MongoDB cast exception - nested subdocument

Check out this schema design: var messageSchema = new Schema({ receivers: [User], message: String, owner: { type: Schema.Types.ObjectId, ref: 'User' } }); var userSchema = new Schema({ name: String, photo: String }); var in ...

Using jQuery ajax to send a Python response back to the original page

I am looking to implement jQuery ajax along with a simple web form containing two fields to transmit values to a python script. The goal is to have the results displayed within a specified div tag on the same calling page (index.html.en). The process invo ...

ng-change not firing when selecting from ng-options list

I am struggling with this code snippet <select ng-model="trabajadores.orderSelected" ng-options="excel for excel in trabajadores.csv.result[1]" ng-change="console.log('changed')"> </select> Despite my best ...

What is the best way to render CSS files in express.js?

My file organization looks like this: node_modules structures {HTML Files} styles {CSS Files} app.js package-lock.json package.json I have already imported the following: const express = require('express'); const app = express(); const p ...

What are the steps to turn off response data compression in an Express server?

How can I receive the 'Content-Length' response from the server without gzip compression enabled? I am using a compression middleware for this purpose: const shouldCompress = (req, res) => { if(req.headers['x-no-comprassion']) { ...

Ways to adjust the number of columns in a div using Bootstrap for varying screen sizes of larger devices

I am new to coding and exploring html, css, and bootstrap. Is it possible to assign varying numbers of columns to a div based on different resolution ranges for larger devices? Specifically looking at the "lg" range which covers laptops and desktops with ...

KeyBy lodash method stores values in an object using the specified property as keys

There are multiple items stored in an array: "objects": [ { "category": "XXXXX", "item_name": "over_pkg_0", "price": 230 }, { "category": "XXXXX", "item_name": "over_pkg_1", "price": 54 }, ...

Preventing the removal of a choice by disabling it in the selector

I have a unique selector that is designed like this: <select id="patientSelector"> <option disabled selected style='display: none;' id="select0"> New Patients to Come</option> <option id="select1"></opt ...

Creating point illustrations with Three.js

Looking to incorporate random points into a web project using Three.js. Here's the current code: <script type="module"> import * as THREE from 'https://threejs.org/build/three.module.js'; import { TrackballControls ...

Ensuring the correct width for a .png image in an email newsletter for Outlook 2013

After creating an email newsletter that works perfectly on all email clients except Outlook 2013, I realized that the image I included is not adhering to the table width specified. Instead, it is defaulting to its own width of 658px. View image here Below ...