Manage the dimensions of elements using Javascript on the client side

Here is a form I created:

<form action="#" enctype="multipart/form-data" method="post" name="..." id="formPhoto" class="fmp">
        <input type="file" name="pho" id="photo" class="inph" accept="image/*">
        <button type="submit" id="subFormPhoto" class="spp">click here</button>
</form>

Additionally, here is the JavaScript code I used:

<script type="text/javascript">
    var inputPhoto= document.getElementById('photo');
    inputPhoto.onchange=function(){var photo= this.value; photo.onload=function(){alert(this.width+' '+this.height);};};
</script>

I'm facing an issue where the

alert(this.width+' '+this.height);
is not displaying. It seems like the photo is not loading properly.

Answer №1

this.value provides the file name as a string, so your photo.onload function is not actually looking at the photo itself but just at a string. If you alert or console.log photo, you will understand what I mean.

You might want to explore the File API, as it is compatible with modern browsers starting from HTML 5.

Here is a functional example of your code:

var inputPhoto = document.getElementById('photo');

inputPhoto.onchange = function() {
  var file = this.files[0];
  var reader = new FileReader();
  var photo  = new Image();

  reader.readAsDataURL(file);
  reader.onload = function(_file) {
    photo.src = _file.target.result;
    photo.onload = function() {
      alert(this.width + ' ' + this.height);
    };
  };
};

Answer №2

I have attempted to interpret your query and create a solution based on what I understood. http://jsfiddle.net/qo8ovmhn/

 <input type="file" name="pho" id="photo" class="inph" onchange="myFunction()">
<img id="view" src=""></img>    
<p id="demo"></p>


 <script>
 function myFunction() {
var x = document.getElementById("photo");
var file = x.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(_file) {
 var img = document.getElementById("view");
 img.setAttribute("src",_file.target.result);
 var height = img.offsetHeight;
 var width = img.offsetWidth;
 alert(width + " X " + height);

 };
  }
</script>

Check to see if this meets your requirements. The input's change event triggers when an image is selected. The image data is read and displayed in an image tag. The image's dimensions are then retrieved from its height and width properties. You can conceal the image by using CSS with visibility:hidden or opacity:0 Avoid using display:none as it will result in a height and width of 0px

Finally, the image dimensions are displayed in an alert.

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

Verify if the key-value pair can be found within a multi-layered object

Is it feasible to identify the existence of a key/value pair in any type or level of object, regardless of its structure being unknown beforehand? For instance: Pair to find: "kod": "REVH" Object: { "names": [{ "name1": "xxx", "name2": "yyy", ...

JavaScript running out of memory during yarn build process

While working with yarn to build my project, I encountered a problem. The issue at hand is that the memory heap exceeds its allocated size, causing the build process to fail. FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - Java ...

"Revamp your site with Vue and API for dynamic background

I'm faced with an issue where I am attempting to modify the background of a joke fetched from an API, but for some reason, the background is not changing and I can't seem to identify why. The main problem lies in my inability to change the proper ...

"An error message is displayed stating that the maximum call stack size has been exceeded while looping through an

Dealing with an array containing 10,000 items and attempting to assign a new property to each item has been a challenge for me. _async.mapLimit(collection, 100, function (row, cb){ row.type = "model"; cb(null, row); }, function (err, collect ...

Tips for adding a personalized close button to a Bootstrap modal

I need help with a Bootstrap modal in my project that has a close button positioned at the top right corner. I've used CSS to position the button, but it's not staying in one place consistently despite applying absolute positioning. I've tri ...

Using vue.js to make an HTTP GET request to a web API URL and display

I am currently utilizing vue.js to make an http request to a web api in order to retrieve a list of projects and display them in a list. However, I am encountering an issue where only one item from the response array of eight items is being rendered. Any a ...

The AJAX request function in JavaScript seems to be failing to return any response

I am currently working on a registration page where users can check the availability of their selected username without having to reload the entire page. The PHP script 'usernameAJAX.php' is responsible for querying the database and returning a r ...

Issues with displaying markers on Google Maps API using JSON and AJAX

I have successfully coded the section where I retrieve JSON markers and loop through them. However, despite this, the markers do not seem to be appearing on the map. Could someone please assist me in identifying the mistake? $.ajax({ url ...

What is the reason behind TypeScript choosing to define properties on the prototype rather than the object itself?

In TypeScript, I have a data object with a property defined like this: get name() { return this._hiddenName; } set name(value) { ...stuff... this._hiddenName = value; } However, when I look at the output code, I notice that the property is on ...

Tips for creating a typescript typeguard function for function types

export const isFunction = (obj: unknown): obj is Function => obj instanceof Function; export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[object String]"; I need to create an isFunction method ...

Is Angular automatically assigned to `window.angular` on a global level when it is loaded as a CommonJS module?

When I import Angular 1.4 in my Webpack build entry point module as a CommonJS module using var angular = require("angular");, it somehow ends up being accessible in the global namespace of the browser (as window.angular). Upon examining the source code o ...

JavaScript code to verify if a checkbox is selected

Having some trouble making a text box value change based on checkbox status. I've attached a function to the onclick event of the checkbox, but it's not quite working as expected. <div> MyCheckbox <input type="checkbox" id="Check1" name ...

Turn off HTML5 Audio

There are 4 <audio> elements on a webpage. The client has asked for them to be available sequentially. Meaning, the first audio should play, then the rest should remain disabled until the first one finishes, and so on. In addition, they want the au ...

What is the process of unmounting the next/script on page change within a next.js application?

Is there a way to load a script only on specific pages? Next.js suggests using next/script tag for this purpose. However, I noticed that even when navigating to different pages, the script remains visible at the end of the HTML body. https://i.sstatic.net ...

Problems with Google Maps Event Tracker

I recently inherited a section of code that utilizes the Google Maps API to place markers on a map along with information windows. Below is an excerpt from the code responsible for creating the markers and setting up event listeners: if(markers.length > ...

When executing a Javascript POST request to a PHP script, it succeeds when running on

I have a simple code that works fine on my website when the PHP file is linked as "/phpcode.php", but it fails to retrieve data when I place the JavaScript request on another site and use the full link. I am currently using GoDaddy as my hosting provider. ...

What is the best way to showcase a chart using jquery?

Is there a way to incorporate trendlines or target lines in highcharts similar to fusion chart? I have been able to draw them successfully in fusion charts. Check out this fiddle link: http://jsfiddle.net/Tu57h/139/ I attempted to recreate the same in hi ...

Moving through divisions that share a common class name using jquery

I am experimenting with a plugin that allows me to attach popups to images. My goal is to enable navigation between all popups using previous and next buttons upon clicking on a popup. Below is the element when it's displayed: <div class="imp-too ...

Using the input type 'number' will result in null values instead of characters

My goal is to validate a number input field using Angular2: <input type="number" class="form-control" name="foo" id="foo" [min]="0" [max]="42" [(ngModel)]="foo" formControlName="foo"> In Chrome, everything works perfectly because it ignores ...

Having trouble with an endless GET request loop in NextJS 13 while utilizing the Next-Auth middleware. Experiencing difficulties fetching the RSC payload

UPDATE: The issue has been identified! It seems that the bug is caused by using the beta turbopack. I have reported this problem and we are awaiting a resolution. Query: I recently delved into a project in NextJS 13 with the new app directory setup. Afte ...