JavaScript - A simple way to retrieve the dimensions of an image consistently

I'm currently working on a piece of Jquery code that is designed to display an image fitting within the screen's dimensions. These images are generated dynamically as needed. However, I am facing an issue where the height and width of the image are set to 0 upon initial loading. Is there a method to reliably retrieve the image size every time?

Here is what my code looks like so far:

var parent = document.getElementById('gallery-lightBox-large'),
    image = originalImages[currentIndex],
    original = document.createElement('img');

parent.innerHTML = '';

original.src = image.Url;

var windowHeight = window.innerHeight * 0.8,    
    windowWidth = window.innerWidth * 0.8;      

original.style.opacity = '0';
original.style.position = 'absolute';
original.style.zIndex = '-99';
parent.appendChild(original);

var elem = document.createElement('img');
elem.src = image.Url;
elem.clientHeight = original.clientHeight;
elem.clientWidth = original.clientWidth;

var width,
    height;

if (windowHeight < windowWidth) {   
    if (original.clientWidth > windowWidth) {
        width = windowWidth;
    } else {
        width = original.clientWidth;
    }

    if (original.clientHeight > windowHeight) {
        width = undefined;
        height = windowHeight;
    } else {
        height = original.clientHeight;
    }
} else {    
    if (original.clientHeight > windowHeight) {
        height = windowHeight;
    } else {
        height = original.clientHeight;
    }

    if (original.clientWidth > windowWidth) {
        height = undefined;
        width = windowWidth;
    } else {
        width = original.clientWidth;
    }
}

if (width != undefined) {
    if (width === 0) {
        width = 200;
    }
    elem.width = width;
}

if (height != undefined) {
    if (height === 0) {
        height = 200;
    }
    elem.height = height;
}

parent.appendChild(elem);

Answer №1

Here is a method you can use to determine the size of an image after it has finished loading:

var image = document.getElementById('imageId');

image.onload = function () {
    alert(image.width + "," + image.height);       
};

Answer №2

Following some helpful advice from Martin Gottweis (Who is more than welcome to provide an answer for me to consider ;-) )

This is the solution I came up with:

var parent = document.getElementById('gallery-lightBox-large'),
    image = originalImages[currentIndex];
var elem = document.createElement('img');
elem.src = image.Url;
parent.appendChild(elem);

and here is the accompanying CSS:

#gallery-lightBox-large img {
    max-height:70vh;
    max-width: 70vw;
}

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

ReactJS input range issue: Cannot preventDefault within a passive event listener invocation

I've been encountering some issues with the react-input-range component in my React App. It functions perfectly on larger viewports such as PCs and desktops, but on smaller devices like mobile phones and tablets, I'm seeing an error message "Unab ...

What is the best way to implement media queries in a column layout for a responsive webpage?

My goal is to display a picture below the navbar when the window size becomes small or in mobile mode, followed by my name and other details. However, I am having trouble understanding how to implement this using media queries. DESKTOP PREVIEW https://i. ...

The function react__WEBPACK_IMPORTED_MODULE_0___default.a.useContext is not recognized when implementing Autocomplete within Material UI

Every time I attempt to create an Autocomplete tag utilizing Material UI, an error pops up, which can be seen in the following link: https://i.sstatic.net/kxKR4.png The Autocomplete code snippet is as follows: import React, {useState, useEffect, useCo ...

Display Nvd3 Pie Chart percentages in decimal format

I have integrated Nvd3 into my Angular project to create various types of charts. Utilizing the angular directive from Krispo's website, I am currently working on a pie chart that displays values in percentages. However, the displayed values are round ...

Use data attributes to automatically populate one form field with the information from another form field using jQuery

Within my Laravel 5 ecommerce website, I am attempting to automatically populate the values in the shipping_address form with the values from the billing_address form if the checkbox with name = same_as_billing is selected. I have been trying to utilize t ...

Make the background image within a button stretch to completely cover the button

I need assistance with creating a button that has a large image as its background. The challenge I'm facing is that the image fits vertically within the button, but horizontally it repeats unless I use 'no-repeat', which leaves empty space i ...

How to retrieve a value from PHP using Ajax?

I am struggling to implement ajax for adding a div to display an error message. Despite my efforts, I keep receiving null as the error message instead of the expected value. The occurrence of null is traced back to <?php echo json_encode($_SESSION[&ap ...

Error message: The Bootstrap .dropdown() method failed because it encountered an "Uncaught TypeError: undefined is not a function"

I've encountered an issue that seems to be a bit different from what others have experienced. Despite trying various solutions, I still can't seem to fix it. I suspect it might have something to do with how I'm importing my plugins. The erro ...

What steps can I take to improve my routing structure in nodejs and express?

My current WebAPI code is pretty modular, but I want to make it even more so. Right now, all the routes are in my server.js file and I would like to separate them into individual controllers. Any suggestions on how to achieve that? Here's an example: ...

Tips on showing binary information as images using extjs 4

As the proud owner of a valid .JPEG image's binary data, I am on a quest to convert this information into an actual viewable image using Python. Seeking advice on how to successfully transform this binary code into a visually appealing .JPEG format w ...

Customizing Drop Down Button in React Material-UI with Conditions

Trying to figure out how to dynamically populate the second MUI dropdown based on the selection from the first dropdown. Currently, I have both dropdown lists hardcoded. const [queryType, setqueryType] = React.useState(''); const [subCategory, se ...

What is the method to apply custom styles (CSS) to individual options within a jQuery UI selectmenu?

When working with an HTML form that includes a select element, I encountered a design challenge. <select id='myselect'> <option value='1'>1</option> <option value='2'>2</option> ... <option va ...

What does the error message "Uncaught TypeError: Cannot access property 'style' of an undefined object" mean?

I've been attempting to execute the code below, but I keep encountering an error. I even tried including document.addEventListener('DOMContentLoaded', (event) => yet it still doesn't work. Interestingly, there are no errors if I run ...

Unable to locate the "fcm-node" module in Node.js with TypeScript

When working on a TypeScript project, I usually rely on the fcm-node package to send Firebase push notifications in Node.js. However, this time around, I faced an issue. I know that for TypeScript projects, we also need to install type definitions (@types ...

Toggle the sliding menu drawer option (upward/downward motion)

When it comes to my simple menu, I'm using jQuery to toggle the visibility of a few DIVs. The code is straightforward as shown below, and I could really use some assistance with adding extra functionalities. <div id="one" class="navLinks"> cont ...

Challenges with Input Nesting

Why is the word "undefined" appearing on top of my text? function printName() { document.write('My name is John Doe.'); } function printAge() { printName(); document.write('I am 47 years old.'); } document.querySelector(&ap ...

Are toggle functionalities triggered when an element is clicked?

How come the span triggers functions a and b when first clicked, is there a way to set it up so that it calls function a on the first click and then function b on the second click? function a(id) { $.post("url.php", {'id':id}, function() { ...

Encountering a PHP issue while attempting to embed Google Trends into an HTML element

I am encountering an issue while attempting to assign the html property of a jquery element to embed Google Trends. <!DOCTYPE html> <html> <head> <title>Titlw</title> </head> <body> <div class="hide ...

An issue arose in Leaflet where drawing on the map became impossible after making an update to a marker's position

I have been working with Leaflet, Leaflet-draw, and Cordova Geolocation. Initially, when the map is loaded in globe view, drawing works perfectly. However, when the locate function is called to update the map center and marker position, drawing becomes imp ...

Is it recommended to use Promise.await over async/await?

After starting some new operations in my project, I discovered that db.aggregate needed to be executed asynchronously: db.aggregate( [ { $match: { "records": { $e ...