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

The input values are displayed in a continuous line without any breaks between them

I'm currently learning ReactJS and I have created a simple example to practice. The goal is to display each input value (separated by whitespace) in an HTML element (<h1>). However, instead of showing each output value individually, they disappe ...

What is the best way to include multiple entries in a select2 form using ajaxform?

select2/3.5.2/ I had to repost this because my initial post was not formatting correctly. The tools in use are: A select2 form field that allows searching through multiple records A bootstrap popup modal containing a form for entering a new record if i ...

Pandoc has removed all the line breaks in this text

I am currently utilizing pandoc for converting HTML to Markdown format. However, I have noticed that Pandoc tends to remove line breaks in the final output. Below is the command I am executing: pandoc -f html -t markdown_phpextra myfile.html Does anyo ...

What could be causing the lack of animation in W3schools icons?

I've followed the steps provided and even attempted to copy and paste them. However, I'm experiencing an issue where the animation doesn't fully execute. Instead of the bars turning into an X shape, they reset halfway through the animation. ...

Why does the control skip the onreadystatechange function for the ajax object?

Just beginning my journey into web-development. Recently, I encountered an issue with a signup page I created that involves asynchronous calls to php. Upon debugging, I noticed that the onreadystatechange function is being completely skipped over. Any assi ...

Discover the second character in the sequence and substitute it with a different numeral

I need to manipulate a string where I want to replace the second digit with a random number. The challenge lies in identifying the second digit and performing the replacement. How can I accomplish this task? 1. "data[KPI][0][rows][0][name]" 2. "data[KPI][ ...

There was an issue with the Weather API: {"cod":"400","message":"{vlat} is not a valid floating point number

I have been working on my local weather app project and struggling to retrieve the API coordinates. Here is the link I am using from Open Weather Map: http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+long+'& ...

What is the best way to implement conditional styling in Vue.js?

Looking to incorporate a conditional style into my Component. Here is my component: <site-pricing color="primary" currency="$" price="25" to="/purchase" > <template v-slot:title>Complete</templat ...

Utilizing jQuery to Extract HTML Data Attributes

Is there a way to access and extract the values stored in the data attributes with jQuery? <div class="sm-tot" data-ts-speed="500" data-ts-interval="4000" data-ts-newVal="5000" > ...

Issues arise with the behavior of Bootstrap design when adapting to different screen sizes, as well as

I am currently working on designing my personal portfolio using Bootstrap. I have made some progress with the setup, but I am encountering some issues. When I resize the window, the top menu collapses into a button. However, when I click on the button, n ...

Unable to sign up for WordPress function

I'm having trouble getting my function registered properly in WordPress, no matter how many times I try. So far, here's what I've done: Inserted code into themes functions.php function test_my_script() { wp_register_script( 'custom-s ...

Error: Unable to Locate CSS File for Wordpress Elementor

Currently in the process of transferring a WordPress website that utilizes Elementor. Successfully migrated both the code and database over. However, upon inspecting the page, I encountered a 404 error indicating that a css file associated with Elementor c ...

Leverage the power of effekt in your AngularJS development

Can anyone demonstrate how to implement animation effects with AngularJS? Has someone created an example using Effeckt.css? ...

The confirmation dialogue is malfunctioning

Need some assistance with my code. I have a table where data can be deleted, but there's an issue with the dialog box that pops up when trying to delete an item. Even if I press cancel, it still deletes the item. Here is the relevant code snippet: ec ...

Changing the CSS background in React when updates occur

Currently working on toggling the CSS background image within this React application. The images have been successfully imported and a variable called "image" is set to the imported image as the iteration increases/decreases with each click. The issue I&a ...

How can I input text into separate tabs using a specific method?

I've been struggling with this issue for a while now and here's the code I have so far: <html> <head> <script src="http://mihaifrentiu.com/wp-content/themes/mf/js/jquery_1.7.1.min.js" type="text/javascript"></scr ...

Ways to verify if options have been chosen or not?

if(isset($_POST["marketing"])){ foreach($_POST as $key => $value){ if(strlen($value)<1) continue; echo "<option value='".$value."' selected >".$value."</option>"; } I have a PHP script that dynamically cre ...

Creating a custom function in a Node.js application and rendering its output in the front-end interface

I've been trying to scrape data from a website and display it using innerHTML, but I'm running into some issues. The code snippet I'm using is: document.getElementById('results').innerHTML = searchJobs(''); However, I ke ...

Adjust the parent element to match the width of the child by utilizing the "display: grid" property

edit: I'm uncertain if this is a duplicate issue. My concern is not about the background color extending beyond the container width, but rather about expanding the container to match the size of its child with display: grid. I have updated the example ...

How can JavaScript routes be used to apply specific code to multiple pages on a website?

Can you provide guidance on how to run the same code for multiple pages using routes? Below is an example I am currently exploring: var routeManager = { _routes: {}, // Collection of routes add: function(urls, action) { urls.forEach(fun ...