Troubleshooting the Ineffectiveness of Setting the CSS Top Value with jQuery

I need to center text vertically within a DIV without using fixed pixel heights, only percentages. Here's my current setup:

<div style="position:relative; width: 100%; height: 100%;">

   <img src="images/thumb-member-placeholder.gif" alt=""  class="myImage"  /> 

    <div class="myText" style="display: inline-block; position: absolute; z-index:500; text-align:center;">Image Text</div>

</div>

I have multiple similar divs with varying text lengths that I want to center vertically.

To achieve this, I am using jQuery to detect the height and set the top value accordingly:

        $(window).load(function() {


          var imageHeight = $('.myImage').height();


          $('.myText').each(function() {

            var textHeight =  $(this).height();


            var vertAdj = ((imageHeight - textHeight) / 2);
            $(this).css('top', vertAdj);

          });

        });

However, this method is not yielding the desired result. The top value remains constant and doesn't adjust for multi-line text in "myText". Any ideas on how to fix this issue?

Answer №1

Give this a try:

$('.contentArea').each(function(i,e) {

            var contentHeight = $(e).height();

            
            var verticalAdjustment = ((windowHeight - contentHeight) / 2);
            $(e).css('position', 'absolute');
            $(e).css('top', verticalAdjustment);

          });

Check out the .each reference for additional details http://api.jquery.com/each/

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

Leverage the AJAX response data for another JavaScript function

I am interested in utilizing the data received from an AJAX response in another JavaScript function. Here is the AJAX call located in the view file (sell_report.php): <script src="<?php echo base_url(); ?>public/js/jquery-1.12.4.min.js"> ...

Performing a Jquery ajax post to an MVC2 action

I have a script set up to send a POST request to an endpoint, and it seems like the routing is correct as it hits the breakpoint on the server. $(document).ready(function() { var o = new Object(); o.message = 'Hi from the page'; $.ajax({ ...

The results of the jQuery selector appear differently in the browser console compared to PhantomJS

What could be causing the discrepancy in results when using the same jQuery selector? Visit this website for reference: See below code involving node.js and phantomjs-node(bridge): phantom.create(function(ph){ ph.createPage(function(page){ p ...

Select the last visible list item element that is not hidden

Looking to work with the last li element: var p = $("li:last"); Trying to retrieve its position: position.left By getting the position, I can align an element accordingly. However, there's an issue if the last li is hidden due to an event.hide, res ...

One blade is successfully utilizing the AJAX URL, while the other blade is experiencing difficulties with it

I have successfully implemented AJAX in Laravel to fetch data from a database. The code for my AJAX call is as follows: $('#salesmanlist_input').on('change', function() { var salesmanlist_input = $(this).val(); ...

slow loading background slideshow in css

Creating a simple slideshow for the background using CSS has been successful, but I am facing an issue with making all backgrounds utilize background-size: cover. I want the images to fit properly on the screen. Another problem is that the pictures take a ...

Using AJAX for fetching and saving an object into a variable

I am dealing with two specific files in my project. The first one is called index.php, where the user initiates an AJAX request. The second one is called process.php, which is responsible for sending data back to the index.php file. function AjaxResponse( ...

Is it possible to customize the default translucent image that appears when the onDragStart event is triggered in a browser?

Hey everyone, I hope you're all doing great. Firstly, I want to express my gratitude for your support in trying to improve my skills. My current project involves developing a simple drag-and-drop feature for an existing list as part of a practice exer ...

Transmit EOF signal to the browser, while progressing with the processing on the server through an ajax request

I am currently utilizing Jquery and PHP for my project. I need PHP to send a response to an ajax call and close the connection without terminating the script execution on the server. My main concern is that I do not want the browser to wait for the server ...

Issues with web display on Android devices

My website is having display issues specifically on Samsung and Motorola devices, even when using different browsers. It seems that the area using transform CSS is breaking apart. You can view my website at I've tried several fixes but nothing seems ...

What Are The Steps to Ensure My HTML CSS Code has an Effective Navigation Dropdown Menu?

Seeking Help with Navigation Dropdown Menu Functionality, as a Beginner Facing Challenges in Understanding I've Put in a Lot of Effort to Make It Work Correctly, but I'm Struggling. Any Solutions and Tips would be greatly Appreciated. ...

PHP handling AJAX request during execution of lengthy script

I recently posted a question on Stack Overflow where I received a satisfactory response that is working perfectly. However, I seem to be facing an issue where all AJAX requests stop functioning when the script runs for more than 4 to 5 seconds until the en ...

difficulties switching content between different screen sizes

Having trouble with hidden-xs and visible-xs-* classes not working as expected. Even a simple code snippet like the following doesn't hide the content: <div class="hidden-xs"> test test test </div> Even when scaling down my window to ...

Ajax RSS Feed - Weather Data from OpenWeatherMap

I am encountering an issue where the feed does not refresh with new news as they come in, even after selecting an option. This same problem is also occurring with openweather. I suspect that everything is being cached when it shouldn't be. Should I ch ...

Guide on how to trigger an alert and confirmation pop-up upon detecting a click on the browser's back

I'm currently developing an exam application using php and jquery. The application includes several pages for creating exams: Create.php (for entering exam details) QandA.php (to add questions and answers) Marks.php (for setting up marks) Penalty.ph ...

Generating Unique Random DIV IDs with JavaScript

Does anyone know of a JavaScript solution to generate unique random DIV IDs? I am currently using PHP for this purpose. <?php function getRandomWord($len = 10) { $word = array_merge(range('a', 'z'), range('A', &apos ...

Adjusting column width in Bootstrap grid when content is missing

Currently, I am encountering a problem with the grid system while attempting to create a kanban style drag and drop system. The issue is illustrated in the image below. Each card should be positioned according to the arrows shown. As the 2nd column is cur ...

Ways to trigger an alert once a div is fully loaded with content

I have a webpage with a search feature. When the user clicks the search button, the results are fetched via ajax from the database and displayed in a div. After the results are displayed, I want to perform an action as soon as the total count of records i ...

Most efficient method for attaching onchange event to all form fields in Rails 3 with UJS/jQuery

I am looking for a way to dynamically update search results count in a separate CSS box whenever a form field's value changes, similar to how it is done on this website. What would be the best and easiest technique to achieve this? PS: I already know ...

What is the best method for incorporating a data-* attribute to every option while configuring a select2 input field?

Currently, I am utilizing the select2 plugin to enable the selection of an image from a list to display on the screen. In order to achieve this functionality, I must assign a specific attribute to each option: s3_key. My requirement is to set this attribu ...