Adjusting the size of an image to be responsive once the document has fully

Struggling with creating a custom carousel/slider element and running into an issue that doesn't seem to make any sense.

Attempting to retrieve image size using jQuery on document load results in incorrect width/height calculations. Initially thought it might be due to the document not fully loaded when the page displays, but even after using the https://github.com/desandro/imagesloaded library, the problem persists.

Luckily, I was tinkering with this on CodePen, so here's the link for reference: Codepen

$( document ).ready(function() {

  $(".carousel").imagesLoaded(function(){
  //shows logo before images are loaded
  $(".logo-container").addClass("hide");
  $(".carousel").removeClass("hide");



  //get carousel dimensions
  const carouselEl = $(".carousel");

  //image
  const imageEl = $("img.active");

  //get active dimensions
  const elWidth = imageEl.width();
  const elHeight = imageEl.height();

  console.log(elWidth,elHeight);

  //set carousel dimensions
  carouselEl.width(elWidth);
  carouselEl.height(elHeight);
  });

});

Am I overlooking something crucial?

Appreciate your assistance.

Answer №1

Your css sets images to have max-width:100vw;, which means they always take up 100% of the screen width, in my case that would be 1920px.

To find out the actual width of an image, you can use: imageEl[0].naturalWidth

Explanation:

[0] converts a jquery object into a native JavaScript HtmlElement (selects the first item in the collection)

By using naturalWidth, naturalHeight, and ViewportWidth, you can calculate the desired height:

Calculate the desired height based on screen width and image aspect ratio.

naturalWidth / naturalHeight = image ratio => should equal: viewPortWidth / desired height.

viewPortWidth / naturalWidth * naturalHeight = desired (scaled) height
, depending on the width/height ratio.

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

Exploring the capabilities of Express.JS for integrating with an external API

const express = require('express'); const app = express(); const path = require('path'); const api = require('./api'); app.get('/', function(req, res){ res.sendFile(path.join(__dirname + '/index.html')); ...

Exploring the differences between utilizing request.body in building RESTful APIs with Django versus Node.js

As I dive into learning the Django framework, my main aim is to leverage this knowledge in creating a rest api. Although I've looked into using django-rest framework, my current job necessitates a focus on Django specifically. In my journey so far, I ...

Elements floating and creating gaps (caused by varying heights)

I am working on developing a responsive webpage. This is what I am aiming to achieve. View jsfiddle #container { max-width:500px; width:100%; color: #fff; } #one { width:300px; height:200px; background:#66BCD9; float:left; } #two { wid ...

Mastering the use of gl Scissor is essential for effectively implementing popups in your

I am attempting to implement a pop-up view on top of the current webGL view. My strategy is as follows: Whenever I need to display a popup, I create a scissorRect and begin rendering the popup scene onto it. I was hoping that the content of the previous s ...

Implementing automatic redirection upon clicking using React without the need for manual clicking

I'm experiencing an issue where the page seems to automatically navigate to another page without clicking on the div. Can anyone explain why this is happening? Here's the code snippet for reference: import React, { Component } from "react&q ...

View a pink map on Openlayers 2 using an iPhone

I am currently working on a project where I am trying to track my location using my smartphone and display it on a map. To achieve this, I am utilizing openlayers 2. However, I am encountering an issue. When I implement the code below in a Chrome Browser ...

text within the table is overlapping when being created dynamically in the <table> using javascript and jquery.quickflip.js

Hello everyone, I am currently working on dynamically generating a table using tabs created with jquery.quickflip.js. However, I have run into an issue where the text from one tab may overwrite values in another tab when switching between them. Below is ...

What is the process for adding an item to an object?

I currently have the following data in my state: fbPages:{'123':'Teste','142':'Teste2'} However, I am in need of a dynamic solution like the one below: async getFbPages(){ var fbPages = {} awa ...

Display a different GIF every time a page is visited or refreshed

I am incorporating the GIPHY API to showcase an image based on a query. The current code I have pulls the image successfully, but there is a recurring issue where the same GIF displays each time the website is visited until the query is altered. My aim is ...

How can I implement long polling effectively with jQuery and AJAX?

Currently, I am working on a project that requires live notifications. I considered using socket.io, but due to time constraints, I decided to explore AJAX and jQuery as alternatives. I have outlined my code structure below and I am curious if this appro ...

Tips for showcasing API responses in HTML

Although I have successfully retrieved the data, I am facing issues with efficiently displaying it on an HTML page. Currently, my solution involves using two endpoints - one to fetch API data and another to load the HTML with a script. However, this appro ...

What could be causing the pause function for videos to stop working in Chrome?

Recently, I've encountered an issue with the pause() function in Chrome while trying to stop a video playback. Despite using this method successfully in the past with Firefox, it seems to no longer work on Chrome browsers. I've simplified my code ...

Running a code from a plugin in Wordpress site

I am currently utilizing the "wp-video-lightbox" plugin for WordPress, which generates small floating boxes for my videos. I am interested in incorporating variables like http://www.example.com/?video3 to provide shortcuts similar to what YouTube offers. ...

variances in CSS performance between local and remote hosting

My team and I are all using Internet Explorer 8 on Windows 7 Professional, with Visual Studio 2010 Premium. However, we have noticed that when running our application in localhost mode versus remote mode (on the server), there are differences in the CSS re ...

Is there a method to uncover the code that controls the display of a <div> element?

As a fresh face at the company, I've been given the responsibility of developing a chart that is similar to one already present on their website. While I have the knowledge and skills to create it, I am struggling to locate the specific code where the ...

Troubleshooting: Error in angular JavaScript due to minification: $injector:modulerr Module Error

After defining my angular code as shown below, I encountered an issue when trying to minify the javascript. The error message displayed was: $injector:modulerr Module Error. angular.module('myModule').controller('MyController', functio ...

The error message received states: "materialize-css Uncaught TypeError: Vel is not defined as

My current setup involves webpack as the bundler/loader, and I've successfully loaded materialize css (js/css). However, when attempting to use the toast feature, an error is thrown: Uncaught TypeError: Vel is not a function The library is being inc ...

Is it possible to identify DOM insertions by using yepnope/modernizer.load()?

Within a windows forms application, we utilize a Master.js file that is referenced following the loading of modernizr. I am defining my modernizer.load tests within a $(document).ready function located at the end of the masterpage.js. This setup allows fo ...

Issue with Bootstrap 5: bg-customcolor and text-customcolor classes are not functioning as expected

Recently, I decided to update an old bootstrap page to the latest Bootstrap 5.3.1 version. Thanks to this amazing guide, I managed to configure my custom colors successfully: How to extend/modify (customize) Bootstrap with SASS However, I encountered a pr ...

Monitoring and recording every server-side interaction within the AngularJS user interface

Is there a way to efficiently display all server side REST actions on the angular js UI of my application? For example, how can I immediately show a message on the GUI when a user is created or when an action fails? I currently store all such actions in a ...