Obtaining the height of an image using TypeScript

I am trying to retrieve the height of an image after it finishes loading. Despite my attempts, the offsetHeight property returns 0 and the other methods do not return any values. I can confirm that the elements are loaded when querying their heights because I successfully set their widths using getElementById and setAttribute right before checking their heights.

* {
  margin: 0;
  padding: 0;
  border: 0;
}

.gallery {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.gallery img {
  width: 100%;
  display: block;
}

The image with the id "6" does exist and has been rendered at the time of these TypeScript calls.

My hypothesis behind trying to get the bottom position was based on the idea that if I could determine the top and bottom coordinates of the image, I could calculate its height without directly retrieving it.

console.log(document.getElementById("6").offsetHeight.toString());
console.log(document.getElementById("6").offsetHeight.valueOf());
console.log(document.getElementById("6").style.height);
console.log(document.getElementById("6").style.bottom);
console.log(document.getElementById("6").style.borderBottom);

HTML

  <div id={{i}} *ngFor="let image of images; let i = index;">
    <img class="img-responsive" src={{image.src}} alt="" (click)="clicked()">
  </div>

Answer №1

Check out the following solution -

let element: HTMLElement = document.getElementById('6');
console.log(element.offsetHeight);

Answer №2

If you're looking to add a useful library, consider installing the following:

npm install image-size --save

For those curious about how to use it, here is some sample code:

var sizeOf = require('image-size');
var dimensions = sizeOf('images/funny-cats.png');
console.log(dimensions.width, dimensions.height);

If you prefer working with Async/Await in Typescript & ES7, check out this snippet:

var { promisify } = require('util');
var sizeOf = promisify(require('image-size'));
try {
  const dimensions = await sizeOf('images/funny-cats.png');
  console.log(dimensions.width, dimensions.height);
} catch (err) {
  console.error(err);
}

You can find more information here.

I hope this guide proves helpful for you.

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

Issue encountered while integrating crispy forms with Django and bootstrap

After developing a sign-in page for my blog using bootstrap and django, I decided to incorporate crispy forms. However, upon attempting to access the page, an error message popped up: TemplateDoesNotExist at /register/. Despite ensuring all redirects and U ...

Difficulty encountered when trying to display multiple 3D models utilizing a URL as the source in conjunction with ar.js and A-frame

Recently delving into coding for A-frame projects has been an exciting learning experience. However, I encountered a setback while setting up a scene with multiple targets in A-frame - one of the 3D models failed to appear despite using a URL just like the ...

Aligning the column to the right to ensure the text is centered horizontally on the screen

<div className={css.title} > <div className={css.row}> <div className={css.columnLeft}> <div className={css.header}>Images</div> </div> <div className={css.col ...

Refreshing the Ionic page by reloading it after navigating to a different URL page

Currently, I am working on an Ionic app where users can edit and view their profiles. After making changes on the edit profile page, the app should automatically navigate to the view profile page. My current issue is that I need the view profile page to r ...

Variables within Angular2 services are resetting when the route changes

I have been utilizing a service to monitor the status of my model. I have several components that need to access the variables and properties of this service. The issue arises when the first component initializes, sets the model, but upon trying to access ...

Create a new CSS rule within a class, and remember to save the changes to

Upon opening page 1.html, I utilize JavaScript to dynamically add a background image to the body of the page. To achieve this, I use the following code: document.body.style.backgroundImage = "url(http://www.example.com/image.jpg)"; This code effectively ...

utilizing a dynamic illustration as the backdrop

Despite my efforts, the canvas on my webpage is taking up the entire screen and preventing me from clicking on the navigation menu. I've tried various solutions like adding div tags and adjusting the z-index without success. Here's a snippet of t ...

The malfunctioning collapse feature in Bootstrap 4 sidebar within an Angular 6 application

I am trying to find a way to collapse and reopen the sidebar when clicking on a button. I have attempted to create a function to achieve this, but unfortunately it did not work as expected. Important: I need to collapse the sidebar without relying on jque ...

Prevent Repetition of Meta Descriptions and Keywords within Next.js

I'm currently working on my website using Next.js. In order to enhance the SEO performance of my site, I am making an effort to steer clear of duplicate meta tags. My Inquiry According to Next's official documentation, they suggest that using t ...

Aurelia Fetch functionality disrupted following recent NPM update

After performing an update using npm on my Aurelia CLI project with TypeScript in Visual Studio 2015, my code utilizing aurelia-fetch-client to communicate with my .NET Core Web API backend started encountering compilation errors. The previous code snippe ...

What is the best way to remove table cells from a TableBody?

Currently, I am in the process of designing a table to display data retrieved from my backend server. To accomplish this, I have opted to utilize the Table component provided by Material UI. The data I retrieve may either be empty or contain an object. My ...

Why does Primeng Lazy loading trigger multiple times when updating the sortField and sortOrder?

Lazyload has been successfully integrated into my primeng-table, <p-table #dataTable [columns]="tableHeader" [value]="tableData" [rows]="10" [paginator]="true" [rowsPerPageOptions]="rowsPerPage" [totalRe ...

An easy tutorial on creating a captivating background animation that moves seamlessly from left to right and vice versa

My goal is to create a dynamic animation using jquery/javascript. I have an image that is 2000px wide and 200px tall, and I want to animate it from left to right, creating a panoramic view by scrolling back and forth continuously. I attempted to implement ...

Error: The property 'push' in Typescript is missing

Hello, I am encountering an issue with React-Typescript within Redux toolkit. The error message I receive is: 'push' does not exist on type 'string | string[] | WritableDraft<Recipe>[] | WritableDraft<{ recipes: Recipe[]; totalAmoun ...

Using PHP and AJAX to dynamically update the second select option in an HTML table, while also adding new rows using a JavaScript function

Within the image shown, I am dynamically adding rows to a table using JavaScript when the button is clicked: function addRow(dataTable) { "use strict"; var table = document.getElementById("dataTable"); var rowCount = table.rows.length; if( ...

When I adjust the page size, the navbar stays hidden after clicking

Trying to implement a toggle button for the navigation bar. The objective is to hide the navbar on screens smaller than 667px and display a toggle button instead. Clicking the button should toggle the visibility of the navbar items. The toggle button work ...

centering pictures vertically on my webpage

Below is the code I am currently working with. It displays an image on the left and a description with a button on the right, side-by-side within the "promo_box_wrapper" container. However, I'm struggling to vertically align the image within its surro ...

Angular 2/NPM: setting up a new directory with all the necessary files for running the application

I'm feeling a bit frustrated, but I'm giving it a shot anyway. Our goal is to create a TypeScript Angular 2 hello world app that we can use as the front end for a Spring app. Currently, we're using the Angular 2 quickstart as our foundation ...

Instructions on how to trigger an http request upon clicking a link, alter the href, and proceed to navigate to the new destination

Here is a piece of code that demonstrates how to modify an a element's href before the user navigates to the new link: <a href="/initial-link" onclick="modifyHref($event)" /> <script> function modifyHref(event) ...

The div is lacking in height

I have 3 divs that belong to the stackContainer class: .stackContainer { position: relative; } Within these divs, I want multiple elements stacked on top of each other. To achieve this, I use the following code: .stackItem { position: absolute; ...