Using Jquery to apply a class if the height of an image is larger than its width

Can someone assist me with a jQuery question regarding adding classes to images?

I am currently working on a DEMO on codepen.io

The issue I'm facing is that the JavaScript isn't adding a class to the image if the height is greater than the width. Is there anyone who can guide me in resolving this?

Below is the jQuery code I have been testing:


$(document).ready(function() {
  var img = document.getElementById('.user_posted_image');
  //or however you get a handle to the IMG
  var width = img.clientWidth;
  var height = img.clientHeight;

  if(width < height){
     $('img').addClass('portrait');
  }
});

Answer №1

Instead of using

document.getElementById('.user_posted_image')
, consider using $(".user_posted_image"). This way, you are targeting elements by their class name with a class selector.

The document.getElementById method is specifically for identifiers, but if you have jQuery available, you can utilize the #idSelector instead. Additionally, you can make use of the jQuery.width() and jQuery.height() methods.

$(document).ready(function() {
  var img = $('#user_posted_image');//jQuery id selector

  var width = img.width(); //jQuery width method
  var height = img.height(); //jQuery height method

  if(width < height){
     img.addClass('portrait');
  }
});
<img id="user_posted_image" src="image.png" width="100" height="150" />

Edit (Demo CodePen): If you are working with multiple images, it's recommended to use the .each method to handle all elements. The first code example only targets one element.

$(document).ready(function() {
  var imgs = $('.imgpreview');//jQuery class selector
  imgs.each(function(){
    var img = $(this);
    var width = img.width(); //jQuery width method
    var height = img.height(); //jQuery height method
    if(width < height){
       img.addClass('portrait');
    }else{
       img.addClass('landscape');
    }
  })
});

Answer №2

If you're looking for a solution like this, check out the following link: http://codepen.io/BramVanroy/pen/MwrJMx

$(document).ready(function() {
  var img = $('.user_posted_image');
  img.each(function() {
    var $this = $(this),
        width = $this.children("img").width(),
        height = $this.children("img").height();
    if (width < height) {
      $this.addClass('portrait');
    } else {
      $this.addClass('landscape');
    }
  });
});

Go through all divs with the specified class and apply CSS classes based on image orientation.

NOTE: To ensure proper execution, make sure images are loaded before running the script. Consider using the imagesLoaded plugin.


If you include the imagesLoaded plugin, your code will resemble the following:

$(document).ready(function() {
  $(".chated-poeople").imagesLoaded(function() {
    var img = $('.user_posted_image');
    img.each(function() {
      var $this = $(this),
        width = $this.children("img").width(),
        height = $this.children("img").height();
      if (width < height) {
        $this.addClass('portrait');
      } else {
        $this.addClass('landscape');
      }
    });
  });
});

Remember to include the plugin in your HTML:

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/3.1.8/imagesloaded.pkgd.min.js"></script>

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

Identifying the empty population of a hasMany property

I'm facing a challenge that seems simple, but I'm struggling to find the solution. Currently, I'm working with Emberjs 2.8. In my model, I have an async: true property set up like this: models/my-model.js import DS from 'ember-data& ...

Tips on Implementing a CSS Variable in a React Component

Is there a way to use content variable with in-line styles in React? I am unsure of how to accomplish this. CSS3 .right::after, button::after { content: var(--content); display: block; position: absolute; white-space: nowrap; padding: 40px 40p ...

Middleware functions in Mongoose for pre and post actions are not being triggered when attempting to save

After carefully reviewing the documentation, I am still unable to pinpoint the issue. The pre & post middleware functions do not appear to be functioning as expected. I have made sure to update both my node version and all modules. // schema.js const sch ...

Bcrypt.compare function working in code but not functioning in chai/mocha tests

I have integrated node.js backend into my project. For encrypting passwords, I am utilizing the bcrypt library. To compare the string password from the request with the hashed password in the database, I am using the bcrypt.compare function. The bcrypt.com ...

Insert an item into a convoluted array

I'm struggling to insert an Object into a complex array. My attempt looks like this: "DUMMY_PLACES[0].todos.byIds.push," but I am unable to make it work. I have an id and content for the object, and the completed property should default to false. I ho ...

The styles order definition in the Material-UI production build may vary from that in development

When using material-ui, an issue arises in the production build where the generated styles differ from those in development. The order of the material-ui styles in production does not match the order in development. In DEV, the material-ui styles are defi ...

When the button is clicked in Jquery, the HTML is loaded into one div while simultaneously hiding the other div

Looking for some assistance with JQuery, as I am relatively new to it. In my project, I have three divs set up - the first serving as the header, the second containing a slideshow of images along with buttons, and the third that should be displayed upon bu ...

Javascript - parsing a string to create a mathematical equation

Suppose I have an image URL structured like this: blabla.com/bla/twofive.hash.png This type of URL can be converted into a JavaScript string. I am interested in learning how to create an array that breaks down the URL based on special characters, such a ...

Removing an entry from the array using AngularJS

I am facing an issue where I am trying to delete a record from the list. When I click on the delete button, it shows as successfully deleted but the record is not visually removed until I refresh the page. I need to delete the record by comparing both emai ...

What is causing the background image size to adjust when the carousel is toggled?

Can you help me understand why the background-image increases in size vertically when transitioning from url/path to url/path2? I need it to stay the same size as it toggles through all the images. What mistake am I making and how can I correct it? Snipp ...

Discover the process of retrieving an element by its ID when dealing with dynamically generated IDs in AngularJS

I am creating a list using the following code snippet: <div ng-repeat="list in fileUploadList"> <div id="{{list}}Upload"></div> </div> Within the controller, I need to retrieve the element by ID, so I am utilizing this line of ...

Issue encountered while trying to import firebase-functions-test for testing using mocha

I've been attempting to configure a Firebase Cloud Functions repository for running mocha tests. However, I keep encountering an error when utilizing import * as firebase from "firebase-functions-test"; or const firebase = require("fire ...

When IntelliJ starts Spring boot, resources folder assets are not served

I'm following a tutorial similar to this one. The setup involves a pom file that manages two modules, the frontend module and the backend module. Tools being used: IDE: Intellij, spring-boot, Vue.js I initialized the frontent module using vue init w ...

Disabling a specific audio element using its ID

Greetings and thank you for taking the time to read my question. I have encountered an issue while attempting to stop an audio element and I am seeking assistance. I am dynamically creating audio elements with parameters, as shown below. var audio = docum ...

Tips for utilizing XMLHttpRequest to instruct a website to take action

Although I have no prior experience with Ajax, I am in need of some guidance to create a simple Chrome extension. Despite searching online, I have not been able to find much information on this topic, which I believe should be straightforward. Request URL ...

How can I utilize data retrieved from $http.get in Vue.js once the page has finished loading?

I'm having trouble figuring out how to trigger a function in Vue.js after an $http.get request has completed. In the example below, I want to automatically select an element of foobar right after the page loads, but it only works when there's an ...

Shoot back two victories in ajax

I am looking to split the output obtained after making an ajax request <input type="text" class="form-control" name="userno" id='stud_id' readonly > <input type="text"name="studentname" id='studentname' readonly > <inpu ...

Alan AI does not support installation on React Native

❯ To install the @alan-ai/alan-sdk-react-native package, run: sudo npm i @alan-ai/alan-sdk-react-native --save > Post installation for @alan-ai/contact: > Copying AlanSDK.js, AlanButton.js, and AlanText.js to destination Mak ...

Item template with dynamic content for pagination directive

My current implementation includes a paginator directive that displays items from an array: .directive('paginator', function() { restrict: 'A', template: '<div ng-repeat="item in items">' ...

Issues with Subject.subscribe occurring beyond the constructor

If you're looking for a straightforward service, I've got just the thing for you. import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class XmlService { items$: Subject<Item[]> = ...