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

Obtaining JavaScript data using Python Selenium Web Driver

I have been attempting to execute a javascript file within a Python script using Selenium WebDriver in order to retrieve the return value from the function. Despite my efforts and research, I have not been successful after spending several hours on this ta ...

The autofocus feature on the textarea in Angular Material Dialog seems to be malfunctioning

Within a web app, I am utilizing the Dialog component from Angular Material. The Dialog consists of only a textarea that is initially empty. I aim to automatically focus on the textarea when the user opens the modal dialog. How can I achieve this? Despite ...

Advancing in the Mozilla fashion

Having an issue with my progress bar design... When viewed in Chrome, the value of the progress bar appears in red due to CSS styling I applied... But when opened in Mozilla, it shows up as a dull grey color. progress[value] { width: 250px; height ...

Angular2: Utilizing filter and search functionalities for an unordered list

Is there a way to implement filtering for an unordered list in Angular using an input field? This specific component creates an unordered list upon page load by fetching data from a JSON file and using the *ngFor directive along with a service. Below is t ...

What could be the reason why this LESS CSS is not taking effect?

Why won't this stylesheet load properly? The desired background color is supposed to be similar to cadetblue. You can view my page with the linked home.less.css at: ...

Having difficulty accessing the 'makeCurrent' property of an undefined object in Angular mobile application

I have followed the steps outlined in the Angular mobile toolkit guide found at https://github.com/angular/mobile-toolkit/blob/master/guides/cli-setup.md My Node version is v4.4.3 NPM version is 2.15.1 The issue arises when I run the command $ ng serve, ...

Serve static files using ExpressJS when a post request is made

My Express server is set up to serve static files for my website and it's working fine: var express = require('express'); var app = express(); var path = require('path'); var p = path.join(__dirname, '../web/public'); app ...

Show a specific div using jQuery fadeIn() when the user reaches the top of an HTML section

The code below has a specific purpose: 1) Determine the current scroll position. 2) Locate the parent article and determine its offsetTop for each .popup_next which represents a section on the site. 3) Calculate an offset value by adding 30px to the off ...

directive does not execute when the <Enter> key is pressed

I recently came across a helpful post on Stack Overflow about creating an Enter keypress directive. After following the instructions, here is my JavaScript code that replicates the functionality: JavaScript var app = angular.module('myApp', [] ...

What is the best way to set checkboxes to default values using a model?

My journey with angular.js continues as I embark on creating my first non-tutorial web app. In this endeavor, I am utilizing two smart-tables and checklist-model for a seamless user experience. The initial table uses a st-safe-src of all_types, containing ...

Utilizing Jquery in the Wordpress dashboard

I attempted to implement basic jQuery functionality in the admin section for a straightforward widget I am working on, using the following code snippets: jQuery("$id").show() and jQuery("$id").hide() Unfortunately, these functions are not functioning as ...

Use the inline IF statement to adjust the icon class depending on the Flask variable

Is it feasible to achieve this using the inline if function? Alternatively, I could use JavaScript. While I've come across some similar posts here, the solutions provided were not exactly what I expected or were implemented in PHP. <i class="f ...

The issue of "undefined is not a function" is arising when trying to use the session in NHibernate with a mongo store

In my MongoDB database, I have a collection named 'Sessions' within the 'SessionStore' to store session state. To manage sessions, I am using express-session. Below is the code snippet used to set up sessions: var session = requi ...

Express Js EJS Layouts encountered an issue: No default engine was specified and no file extension was included

Hey there! I'm currently experimenting with implementing Express EJS Layouts in my application. However, as soon as I try to include app.use(expressEjsLayouts), an error is being thrown. The application functions perfectly fine without it, but I reall ...

Move the button text back to its original position with animation

I have a button with text that shifts to the right by 15px when hovered over. However, when the cursor is removed, the text immediately snaps back instead of smoothly transitioning back to its original position. I tried setting the ease-in-out property but ...

What is preventing me from making a call to localhost:5000 from localhost:3000 using axios in React?

I have a React application running on localhost:3000. Within this app, I am making a GET request using axios to http://localhost:5000/fblogin. const Login = () => { const options = { method: "GET", url: "http://localhost:5000/fblogin", ...

Tips for concealing a parent element while inside a span with jquery

Beginner asking for help! Take a look at what I've coded: <div class="Links"> <a href="/testthis1.html" data-id="button1"> <img class="icon" src="/test1.png" alt="test1"> <span>Test 1</span> < ...

Transform the jQuery each method into vanilla JavaScript

I have a script that displays a dropdown in a select box. The current script I am using is as follows: jQuery.each( dslr, function( index, dslrgp) { var aslrp= dslrgp.aslrp; jQuery.each( aslrp, function(index2, pslrp) { var found = 0; ...

Is ajax testing with therubyracer (or execjs) worth trying out?

I'm looking to challenge myself by integrating and testing JavaScript code within a Ruby environment. My main goal is to utilize Ruby to set up the database, interact with it using my JavaScript model, and verify the JavaScript state without resorting ...

Learn the process of sending code to a database using AJAX

I am facing a challenge in saving HTML and Javascript codes to a Database using Ajax. I am unsure about the optimal way to do this. Writing all the codes as Strings for the variable seems cumbersome. Do you have any suggestions to simplify this process? & ...