Troubleshooting image overlay alignment concerns

My script successfully adds the image src to the overlay's image, but I encounter a problem when creating the variable imgH for the margin-top value. It calculates the image's height and divides it in half.

The issue arises when the calculated height ends with .5, so I incorporated safeInt = Math.floor(iH) to eliminate any decimal from the value.

In my portfolio, the image centering appears erratic or sets the overlay margin to 0. I am unable to pinpoint what is preventing the variable from correctly aligning the image.

I have some experience with jQuery, so I apologize if this mistake seems basic.

Below is the jQuery code:

function imgOverlay() {
    $('.codeCont img').on('click', function() {
        var imgData = $(this).attr('data');

        $('.overlay').fadeIn().find('img').attr('src', imgData);

        if ($('.overlay img').attr('src') === 'images/vec-3.jpg') {
            $('.overlay').addClass('imgLong');
        }
        else {
            $('.overlay').removeClass('imgLong');
        }

        $('.close').on('click', function() {
            $('.overlay').fadeOut();
        });

        var iH = $('.overlay img').height()/2,
            safeInt = Math.floor(iH),
            imgH = "-" + safeInt + 'px';

        $('.overlay').css({
            'margin-top' : imgH
        });
    });
}

imgOverlay();

Here is the fiddle showcasing the issue: Demo - When cycling through the images from left to right, you will observe inconsistent behaviors with the margin-top.

For a clearer view of the problem, visit the site directly: Direct Link to Site

Answer №1

Make sure to wait for your image to fully load on the page before calculating its height and setting the margin top. You can achieve this by using a load handler for the image like the example below:

function handleImage() {
   ...
   $('.image-container img').load(imageLoadHandler);
}

function imageLoadHandler()
{
   var imgHeight = $('.image-container img').height()/2,
            roundedHeight = Math.floor(imgHeight),
            marginTopValue = "-" + roundedHeight + 'px';

    $('.image-container').css({
      'margin-top' : marginTopValue
    });
}

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 center align an HTML page on an iPhone device

I am currently testing a HTML5 webpage on my iPhone, utilizing CSS3 as well. The page appears centered in all browsers except for the iPhone, where it is left aligned. I have attempted to use the following viewport meta tag: <meta name="viewport" conte ...

How to achieve a seamless iframe effect using CSS

With the introduction of new HTML5 iframe attributes, there are now more options available. One such attribute is the seamless attribute, which has the ability to: Create an iframe that appears to be seamlessly integrated into the containing document. ...

What is the best way to horizontally align a button with CSS?

I need help with positioning a button on my web page. The button looks great, but it's currently off to the left and I want it centered below the main text. Any suggestions on how to achieve this? <!DOCTYPE html> <html lang=""> <head& ...

Updating Vue.js asynchronously using JavaScript import

I am facing a challenge with two form components that share a common JS validator. import { validateInput } from './validateInput.js' export default { data () { return { email: '<a href="/cdn-cgi/l/email-protection" class="_ ...

Quantify the Proportion of Affirmative/Negative Responses and

I am attempting to calculate the percentage of "Yes" or "No" responses in an HTML table based on user input for each month's questions. Then, I want to display the average percentage in the "average" column for each month. For example, if the user sel ...

Integrate new functionality into the plugin's JavaScript code without directly editing the JS file

I need to incorporate a new function called 'setInputDataId' at the same level as the existing function '_select' in the plugin js file without directly modifying the file itself. I am seeking guidance on how to add this new function. ...

The utilization of Display Flex resulting in the enlargement of the containing div

I am currently learning CSS and trying out some new things. I am looking to create a page with two side-by-side divs: one for the sidebar and the other for the main content. My goal is to have the sidebar take up 400px of width and allow the content part t ...

Preventing Body Overflow Without Affecting Iframe Overflow in Meteor.js

Currently, I am working on a project using Meteor for a Point of Sale (POS) system. For those unfamiliar with it, Meteor is a framework that allows for the use of JavaScript, jQuery, and various other web app scripting languages. The goal of this applicati ...

Guidance on using AJAX to update select box options based on the selection from another select box

I am currently working on a popup form that includes two drop-down menus. The challenge I am facing is that the options in the second drop-down menu need to change based on the selection made in the first one. This requires me to retrieve information from ...

issue in jquery: ajax promise not returning any value

My code snippet: var testApp = (function($){ var info = [{ "layout": "getSample", "view": "conversations", "format": "json", }]; var Data = 'default'; function fetchInfo(opt) { return new Promis ...

Cloning a file input does not retain the uploaded file in the cloned input. Only the original input retains the uploaded file

Whenever I duplicate an input type file, I encounter an issue where the uploaded file from the duplicated input is also linked to the original input. It seems like the duplicate input is somehow connected to and taking files for the original one. This is ...

I customized the navbar in Bootstrap by centering it with custom CSS, but whenever I click on it, it suddenly shifts to one side. I'm puzzled as to why this is happening and

I attempted to center my navbar-toggler element, but was only successful in centering the navbar-contend using Bootstrap. I then took it a step further by trying to center the navbar-toggler icon with custom CSS, however, it now shifts to the left when cli ...

Shabuninil's FileUp with a Twist: Undefined Event for Progress Bar

I've managed to get the code functioning from this source, except for the progress bar. The issue seems to be that the "event" variable is not defined when the "onProgress" function is called. While debugging, I noticed that the event is defined in ot ...

Can a form be submitted to two different pages based on the button name?

I have a form that directs to another page and performs various database operations. <form id="form1" method="post" action="goes_to_page1.php" onsubmit="return checkformvalidation();"> <input type="text" id="field1" name="field1" onblur="checkva ...

Encountering difficulties while using JavaScript to complete a form due to issues with loading the DOM

Currently, I am attempting to automate the completion of a multi-page form using JavaScript. Below is the script that I am utilizing: // Page 1 document.getElementById("NextButton").click(); // Page 2 completion(document.getElementById("Rec ...

Searching for a different method in JavaScript that can add items without duplication, as the prependTo function tends to insert multiple items

Every time my code runs successfully, a success message is generated and displayed using prependTo within the HTML. However, the issue arises when the user performs the successful action twice, resulting in two success messages being shown on the screen. ...

What makes the transparent border colors on <tr> appear too dark?

For instance, take a look at this code: http://jsfiddle.net/WaJy7/ In my attempt to apply a semi-transparent border to every <tr> element, I've encountered an issue where the color of the border appears darker than intended for all rows except ...

"Troubleshooting cross-domain issues with iframes in Internet Explorer

My application is built with angularjs and we offer the option to embed it on other websites. Everything works well in IE11, but when the application is iframed onto a different domain's website, it stops working. I've tried adding <meta htt ...

After implementing ajax jQuery with Laravel 10, this page is experiencing technical difficulties

Seeking assistance from experienced individuals in dealing with Ajax jQuery within the context of Laravel. I have encountered a problem that has proven difficult for me to resolve on my own. Sample html code: <li> <a href="" onclick ...

The CSS method for changing the content URL is experiencing difficulties in Firefox

Css: .woocommerce-placeholder.wp-post-image { content: url("DSC0926-1.jpg"); } /*for firefox*/ .woocommerce-placeholder.wp-post-image::before { content: url("DSC0926-1.jpg"); } HTML <img src="placeholder.png" alt="Placeholder" class="woocomm ...