Determining the orientation of an image in JavaScript

Currently, I am attempting to determine the orientation of images using JavaScript in order to apply a specific class to them. This process seems to be functioning correctly on Firefox, but is presenting challenges on other browsers. It appears to work better with smaller images, leading me to believe that it may not be executing properly if the images are not fully loaded. Unfortunately, despite my efforts, I have been unable to find a solution to address this issue. Any help would be greatly appreciated!

Here is the code snippet I am currently using:

$(document).ready(function() {
$('.gallery a').find('img').each(function() {
var imgClass = (this.width / this.height > 1) ? 'landscape' : 'portrait';
$(this).addClass(imgClass);
})
});
.gallery {
display: flex;
flex-wrap: wrap;
width: 450px;
}
.gallery a {
width: 200px;
height: 200px;
display: flex;
justify-content: center;
overflow: hidden;
}
.gallery a img.landscape {
align-self: center;
height: 100%;
filter: sepia(100%);
}
.gallery a img.portrait {
align-self: center;
width: 100%;
filter: grayscale(100%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gallery">
<a href="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
<img src="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
</a>
<a href="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
<img src="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
</a>
<a href="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
<img src="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
</a>
<a href="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
<img src="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
</a>
</div>

Answer №1

To begin with, it is important to implement a check to see if the image has finished loading; if not, you should add an event listener to initiate the loading process.

The loaded status of an image can be determined by checking if its width and height values are greater than 0. If these values equal 0, then the image has not been loaded. The reason why this may work in Firefox is due to the browser caching the images, resulting in them being loaded immediately.

A solution similar to the following code snippet can help resolve the issue:

function setImageClass(img) {
    var imgClass = (img.width / img.height > 1) ? 'landscape' : 'portrait';
    $(img).addClass(imgClass);
}

$(document).ready(function() {
    $('.gallery a').find('img').each(function() {
        if (this.width > 0) {
            setImageClass(this);
        } else {
          $(this).once('load', function () {
            setImageClass(this);
          });
        }
    })
});

Answer №2

After much searching, I've discovered the solution! In order to retrieve the original values of an image, it is best to use naturalWidth and naturalHeight. For those who are interested, here is a snippet of code that works across all browsers. Big thanks to Samanime!

function setImageClass(img) {
var imgClass = (img.naturalWidth / img.naturalHeight > 1) ? 'landscape' : 'portrait';
$(img).addClass(imgClass);
}

$(document).ready(function() {
$('.gallery a').find('img').each(function() {
if (this.naturalWidth > 0) {
setImageClass(this);
} else {
  $(this).once('load', function () {
setImageClass(this);
  });
};
})
});
.gallery {
display: flex;
flex-wrap: wrap;
width: 450px;
}
.gallery a {
width: 200px;
height: 200px;
display: flex;
justify-content: center;
overflow: hidden;
}
.gallery a img.landscape {
align-self: center;
height: 100%;
filter: sepia(100%);
}
.gallery a img.portrait {
align-self: center;
width: 100%;
filter: grayscale(100%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="gallery">
<a href="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
<img src="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
</a>
<a href="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
<img src="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
</a>
<a href="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
<img src="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
</a>
<a href="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
<img src="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
</a>
</div>

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

Enable compatibility with high resolution screens and enable zoom functionality

My goal is to ensure my website appears consistent on all screen sizes by default, while still allowing users to zoom in and out freely. However, I've encountered challenges with using percentages or vh/vw units, as they don't scale elements prop ...

Is there a method to redirect and display a JavaScript message efficiently?

Once the user has updated a record, I want to automatically redirect them to another page where they will be notified with a JavaScript message (alertify.notify()) confirming that the update was successful. I am unsure if it's possible to dynamically ...

Analyze XML elements and retrieve their associated content

Analyzed below are the contents extracted from the processed XML file: <dblp> <incollection> ...

A single Modal, Ajax, and data that is continuously refreshed

I'm currently facing a challenge in my project as I try to implement Ajax functionality. Although I'm relatively new to using it, I believe I have a basic understanding of its workings. My website involves collecting form data, posting it to a d ...

The footer is being obscured by the sidebar

#contents { width: 1100px; margin-left: auto; margin-right: auto; } #sidebar { padding: 10px; position: sticky; top: 20px; left: 10px; width: 150px; border-right: 1px solid black; float: left; } #main { padding: 15px; margin-left: ...

Is there anyone who can provide a straightforward solution (code) for < something basic?

I have learned a lot about programming, but I'm stuck on one thing. How can I make an image stay in place when clicked on? What I mean is that when you click and hold on the image, then move the cursor, the image moves with the cursor. What I want is ...

Issue with creating a new jstree node

I recently put together a basic jstree. When I click on a link, it triggers the createNode() function. This function utilizes the create feature from the API to generate a new node. It appears to be a common issue with jQuery that I am encountering. Any ...

Difficulty encountered in aligning items within neighboring table cells vertically

Currently, I am facing a styling issue with a few table rows. In this particular screenshot: https://i.sstatic.net/FcmJW.png The cells in the blue and red circles are part of a table row (with a height of 50px). Both are set to "vertical-align:top". The ...

Is it common to encounter a "no such file or directory" error when running Docker-Compose with the command "ENTRYPOINT ['./init.sh']" in a Dockerfile?

Contemplate the docker-compose configuration : version: '3.0' volumes: data: driver: local networks: simple-network: driver: bridge services: postgres: container_name: postgres image: postgres ...

Symfony2 AJAX form field updateIs Symfony2 form field update with

Here is a form I have: <form action="{{ path('book_create') }}" method="post" {{ form_enctype(form) }}> {{ form_start(form) }} {{ form_row(form.bookFoto) }} {{ form_row(form.bookTitle) }} {{ form_row(form.categories) }} < ...

Updating MySQL TINYINT Value with AJAX in Bootstrap Toggle Without Reloading Page

Within my application, I aim to modify a boolean state stored in my MySQL database as a TINYINT [0,1] by toggling the state of a checkbox styled like a toggle using the bootstrap toggle plugin. Quite the mouthful, right? The challenge lies in updating the ...

When an AJAX call is made during a PHP session that has timed out

I am working on an AJAX form that handles data authentication. In the event of a session timeout, I need to implement a redirect to the login page. How can I go about achieving this? Here is an excerpt from my simplified server-side code: function doExecu ...

Filtering array objects based on elements in another array

I am trying to filter out elements from one array based on matching ids in another array. My first array looks like: const toFilter = [1,4,5] And the second array has a structure similar to this: const foo = [{id: 1, time:XXX}, {id:2, time:XXX}, {id: 3, t ...

Using AngularJS to iterate through JSON data

I received JSON data from my Facebook account and saved it in a file called facebook.json. Next step is to retrieve and process the data from the JSON file in my controller. app.controller('Ctrl', function($scope, $http) { $http({metho ...

Issue with Achieving Two-Way Binding in Angular 1.5 Component when using $ctrl

I am struggling with customizing some products using a component in my index.html. Ultimately, I need to calculate the total of selected products within the main controller "planosVoz" using two-way binding on the svaTotal property in the component control ...

AFRAME - Enhanced scene overlay

I am currently exploring ways to implement an overlay menu on top of an A-FRAME scene. A great example of what I am aiming for can be found on this website -> By clicking on one of the tiles in the home menu, you will see that the previous scene is mo ...

The elements on the webpage are spilling over with content

I encountered an issue while creating a dashboard with a sidebar on the left side. When adding content to the page, some of it ended up hidden behind the sidebar. I tried using overflow-x:auto and this was the result: https://i.stack.imgur.com/5qHJY.jpg Be ...

Is there a way to make changes to a pre-uploaded PDF document?

I'm looking to include a footer in a PDF file that is currently stored on the server. For instance, I have uploaded a file to uploads/aaa.pdf and now I need to insert a footer into the same file located at uploads/aaa.pdf Does anyone know how I can ...

Select a Date: Input for Date Selection

Is it possible to restrict the selection of certain days using HTML date input validation? Some booking websites have a feature where an interactive calendar only allows users to select specific dates for events, while others are greyed out and cannot be c ...

How to use JQuery to automatically scroll to the bottom of a

I've encountered an issue with my chat conversation update function. It runs every 2 seconds, but whenever I scroll up to read older messages, the page automatically scrolls down again when it updates. This is preventing me from reading old messages p ...