Executing a jQuery script on various elements of identical types containing different content (sizes)

I am currently working on a jQuery script that will center my images based on the text block next to them.

Since I am using foundation 5, I have to use a jQuery script to override the CSS instead of using vertical-align: middle.

The script looks like this:

$(function(){
    var row = $('.row').css("height");

    var center = $('.center');
    center.height(row);

    var centered = $('.centered');
    var imgSize = parseInt(centered.css("height")) / 2;
    var rowInt = parseInt(row);
    var top = (rowInt / 2) - imgSize;
    centered.css({"margin-top" : top + 'px'});

});

This script essentially sets the image column to match the height of the parent row, then adjusts the margin-top of the image to be half the height of the column minus half the size of the image.

While it works for the first column, it applies the same height and margin to all subsequent rows.

To see the script in action, check out this FIDDLE (make sure the jsFiddle results window is wide enough for the correct layout).

What I'm looking for is a way for the script to run on each individual row and handle any additional rows that may be added later on.

Cheers!

Answer №1

In order to achieve the desired results, it is necessary to execute this process for each row individually rather than relying on a single calculation formula. The solution involves looping through each row and performing the operations within that specific row:

$(function(){
    $('.row').each(function() {
        var thisRow = $(this);
        var rowHeight = thisRow.css("height");

        var center = thisRow.find('.center');
        center.height(rowHeight);

        var centered = thisRow.find('.centered');
        var imgSize = parseInt(centered.css("height")) / 2;
        var rowInt = parseInt(rowHeight);
        var top = (rowInt / 2) - imgSize;
        centered.css({"margin-top" : top + 'px'});
    });
});

Updated Fiddle (The variable name row has been changed to rowHeight for improved clarity)

An important aspect of jQuery's getter/setter functions (css, html, attr, val, etc.) is their asymmetrical behavior: Setting a value affects all elements in the jQuery set, while getting a value retrieves it only from the first element. Therefore, using $('.row').height() retrieved the height of the initial row, and subsequently applied those values to all .center and .centered elements.

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

"Assigning a CSS class to determine the length of a List in a JSP

In my JSP code, I have a list called ${contentList} that contains product information such as product images, names, and prices. To display this data in an HTML table using JSP, I want to dynamically set the class of the first table row based on the numbe ...

Incorporating a class into ever-changing Bootstrap Table rows

Looking to enhance my table rows with a class, excluding the header. Struggling to find a way to do this. Any ideas? This is the table in question: <table id="table" class="hidden table table-bordered table-striped table-hover"> <thead> ...

Send a triggering function to two separate components

My objective is as follows: render() { return ( <div> <Child onTrigger={xxx} /> <button onClick={xxx} /> </div> ) } Upon clicking the button, I wish for some action to take place in ...

Placing numerous meshes that are mostly alike but not exactly the same in a scene

We utilize a single geometry that is attached to every mesh within our scene. var geometry = new three.PlaneGeometry(1, 1, 1, 1), Each object has a texture that is generated and cached to form a new material and a mesh for the object. this.material = ne ...

Ways to convert a PHP array into a JavaScript array

I have a 3D array in php when using var_dump($arr) it looks like this array(2) { [0]=> array(4) { [0]=> array(2) { [0]=> string(7) "36.3636" [1]=> int(8) } [1]=> array(2) { [0]=> string(7) "27.2727" [1]=> int(5) } [2]=> a ...

Utilize the Bootstrap grid layout to create space for empty columns on the left-hand

Is it possible to use CSS to ensure that empty columns in a predefined bootstrap grid are on the left rather than the right, without manually adding empty entries into the left hand columns? For example, if the column count is 4 (col-xs-3) and there are 5 ...

The HTML footer designed with bootstrap is not behaving as expected. It is not staying fixed at the bottom of the page and is not displaying at full width despite my coding efforts

Working on a small Sinatra app with bootstrap for layout, I'm encountering some issues. The layout is not sticking to the bottom and not displaying at 100% width as intended. Additionally, the footer text is not centering even after applying the text ...

Bootstrap navbar partially collapsed with inner items concealed not at the edges

Many discussions have come up regarding partially collapsing Bootstrap navbars, such as: Item1 Item2 Item3 Item4 Item5 Is it possible to achieve the following collapsed format: Item1 Item2 Item3 =menu= Or: =menu= Item3 Item4 Item5 This method ...

Unable to set up npm for node-resemble on macOS

Issue Encountered: Error installing node-resemble package due to missing README data and configure errors. npm install failed with exit status 1. ...

Forward to a task with a unique identifier obtained through asynchronous JavaScript calls

I am currently working on an application that utilizes AJAX with FullCalendar functionality. My goal is to enable users to click on a specific item on the calendar, prompting a dialog box with a "View Details" button. Clicking on this button should redire ...

Problem with layout design (utilizing float properties)

I'm curious why the paragraph content gets sandwiched between two floated divs. I'd like the paragraph content to appear below the header. Also, why aren't the line breaks showing in the paragraph? Check out this JS Fiddle link for referenc ...

Accessing index.html via file:// from Vue-cli template

Whenever I execute the npm run build command using this Vue-cli template, it displays this message: Hint: The built files are designed to be served over an HTTP server. Attempting to open index.html via file:// will not function correctly. Therefore, the ...

display alternative text before an image is loaded on the screen

Is there a way to display text instead of an image before the image loads? I have a website with an image as the title, causing the page to load fully before the title image is loaded later. Is there a solution for this issue? ...

Is it possible to update labels on an AngularJS slider using a timeout function?

I recently started implementing an AngularJS slider to navigate through various date and time points. Specifically, I am utilizing the draggable range feature demonstrated in this example - https://jsfiddle.net/ValentinH/954eve2L/ The backend provides the ...

Utilizing props to define the background-color of the '&:hover' state

I'm adapting Material UI's Chip component to accept custom values for the colors prop, rather than being limited to "primary" and "secondary". Additionally, I want the chip to exhibit a hover effect when clicked, transitioning to a different colo ...

Tips for showcasing personalized validation alerts with jQuery in the HTML5 format?

One of the Javascript functions I designed is for validating file extensions before uploading: function validateFileExtension(field, extensions){ file_extension = field.val().split('.').pop().toLowerCase(); if ($.inArray(file_extension,exten ...

Creating a scoreboard layout with HTML and CSS

I am attempting to create a scoreboard in the following format: 0 - 0 Home - Away The issue I am facing is that if the length of the Home team's name is longer, it pushes the dash (-) further. I want the dash to be a ...

Looking for assistance in implementing specific styling techniques with React

Trying to implement a slider on my React page sourced from a Github repository. The challenge lies in adding the CSS as it is in JS format. Even after incorporating webpack and an npm compiler, the styling seems unrecognized. Any suggestions or solutions ...

What is the mechanism behind jQuery triggering the execution of JavaScript code contained in script tags that are retrieved in an AJAX response?

What is the unique ability of jQuery that allows JavaScript code inside script tags in an AJAX response to be executed? In the absence of jQuery AJAX, using eval() has been a common method to achieve this functionality as discussed in posts such as: Cal ...

Issue with AngularJS: Dynamically generated tab does not become active or selected

Exploring an AngularJS code snippet that generates tabs upon clicking the new button. However, there's an issue where the newly created tab doesn't become active or selected automatically after creation. It seems like the one before the last tab ...