Adjust image size according to the browser's window resize using JQuery

I am trying to make an image resize based on the browser size changes using JQuery.

My goal is for the image to scale without losing its aspect ratio or getting cropped.

I have incorporated Bootstrap in my HTML structure:

<div class="container-fluid">
      <div class="row">
        <div class="col-sm">
          <div class="text-block">
            <h1>Hello World</h1>
            <h6>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</h6>
          </div>
        </div>
        <div class="col-sm img-container">
          <img src="image.png" />
        </div>
        <div class="col-sm">
          <div class="text-block">
          <h6>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</h6>
          </div>
        </div>
      </div>
    </div>

The image is contained within the .img-container div and my JQuery implementation is as follows:

$(document).ready(function() {
   $(window).resize(function() {
     var img = $("img");
     var image = $(".img-container").find(img);
     var browserRatio =  $(this).width() / $(this).height();
     var imageRatio = image.width() / image.height();

     if(browserRatio > imageRatio) {
       $(".img-container").find(img).css({ "width": "100%", "height": "auto"});
     }
     else if(imageRatio > browserRatio) {
       $(".img-container").find(img).css({ "width": "auto", "height": "100%"});
     }

     console.log("Browser ratio is :" + browserRatio);
     console.log("Image ratio is:" + imageRatio);
   });
});

I aim to adjust the image's dimensions by comparing the ratios of the browser and the image, but it's not functioning correctly. The image width does not retain its original ratio. What could be the issue with my code?

Answer №1

A recent question was addressed using CSS in a straightforward manner here

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

img {
  padding: 0;
  display: block;
  margin: 0 auto;
  max-height: 100%;
  max-width: 100%;
}

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

I am experiencing an issue where the Laravel URL is not being passed to the controller

In my project, I am utilizing ajax along with Laravel 5.4. The issue I am facing is that when the ajax function is executed, it successfully returns the email but does not display the URL page in the console window. Here is the code for the Ajax function: ...

Monitoring the "signed in" status within an AngularJS platform

I'm feeling a bit lost as I navigate my way through Angular. As a newcomer, I find myself writing quite a bit of code to keep track of the logged-in state. However, this approach seems fragile and unreliable. Currently, I rely on a global variable to ...

Utilizing JavaScript to trigger an email with PHP variables included

i am trying to pass a few php variables using a javascript trigger. Everything seems to be working with the variables, databases, and script but I am struggling with the PHP part. Here is my attempt at the PHP code, although it clearly has some issues. I ...

How to precisely navigate to a particular row in a GWT FlexTable

Is it possible to scroll a flextable to a specific selected row? I am attempting to implement functionality where I have two panes, LeftView and RightView. When an item is selected on the RightView, the FlexTable in the LeftView should automatically scrol ...

Instructions on adding an activity indicator in a centered box with a loader inside

I'm currently working on integrating an Activity Indicator into my Vue Native App, but I've been facing some issues as it doesn't seem to be displaying the Activity Indicator properly. Here is the code snippet I've tried: <Absolute ...

What steps can be taken to prevent relying on static file names in the code

Currently, my web application project is being bundled using webpack. The webpack configuration in use is outlined below: const HtmlWebPackPlugin = require("html-webpack-plugin"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const path = requ ...

Utilizing jQuery to access data stored locally

How can I retrieve and display all the values with key 'Task'? Below is the structure of the JSON data: {"Assignments":[{"AssignedBy":"537000","AssignedBy_FirstName":" JOHN","AssignedBy_LastName":"WANDER"}, {"AssignedBy":"537000","AssignedBy_Fir ...

Attempting to transfer information between components via a shared service

Currently, I am utilizing a service to transfer data between components. The code snippet for my component is as follows: constructor(private psService: ProjectShipmentService, private pdComp: ProjectDetailsComponent) { } ngOnInit() { this.psSe ...

Creating a CSS Grid with Scroll Snap functionality to mimic an iPhone screen in HTML

I have created an iPhone simulator using HTML. It's in German, but I can provide a translation if needed: // JavaScript code for various functionalities related to the iPhone interface /* CSS styling for the iPhone interface */ <meta name="v ...

Uncertainty surrounding the application of class selector within CSS

Currently, I'm deep into my CSS learning journey on Progate.com. I've been cruising through the exercises, but I hit a roadblock when it comes to a specific class selector in the CSS code. The task at hand is simple: I need to tweak the CSS so th ...

I am having trouble accessing the div. What could be causing this issue?

Here is the code I have written: - <html> <head> <title>Pranav Sharma</title> <style> @import url(http://fonts.googleapis.com/css?family=Lato:300,400,700); body { background: #ecf0f1; font-fami ...

Javascript continues to execute even after the designated element has been eliminated or substituted

I'm currently working on a WordPress auction site using WooCommerce that needs a countdown timer to display when a specific product auction is ending. Below is the JavaScript code for the countdown timer: const getElem = elem => document.q ...

When converting to a React Functional Component using Typescript, an error occurred: The property 'forceUpdateHandler' could not be found on the type 'MutableRefObject<Spinner | null>'

Looking to convert the App component in this CodePen into a Functional component using Typescript. Encountering an error when attempting to run it: ERROR in src/App.tsx:13:14 TS2339: Property 'forceUpdateHandler' does not exist on type 'Mu ...

Tips for successfully including a positive sign character in string values within JSON in the URL's hash fragment

I am facing an issue with my JS (Angular) app where I load parameters from the URL fragment after the # sign. These parameters contain JSON objects, like this example: ...#filters={"Course":["ST_12.+13.12.2016 [Basel]"]} The aim is to open a data-grid an ...

Implementing mouse event listeners on dynamically created elements in Vue.js

I've been curious if anyone has attempted something similar to the following code snippet (created within a Vue.js method): for (let i = 0; i < this.items.length; i++) { let bar = document.createElement('div'); bar.className = this ...

What does arguments[0] represent when using the execute_script() method with a WebDriver instance in Selenium using Python?

I'm currently in the process of crawling specific pages that catch my interest. In order to do so, I need to eliminate a particular attribute from an HTML element - specifically, the 'style' attribute is what I aim to remove. To achieve this ...

Why does jQuery utilize the anonymous function wrapper?

When delving into jQuery's code structure, one notices that it begins by enveloping all of its code within an anonymous function: (function ( window, undefined) { /* ...jquery code... */ }) (window); It is clear that this function is immedi ...

Is this code in line with commonly accepted norms and standards in Javascript and HTML?

Check out this Javascript Quiz script I created: /* Jane Doe. 2022. */ var Questions = [ { Question: "What is 5+2?", Values: ["7", "9", "10", "6"], Answer: 1 }, { Question: "What is the square root of 16?", Values: ["7", "5", "4", "1"], Answer: ...

Saving a boolean option (Yes or No) via a radio button in a MySQL database

When it comes to storing Yes/No form radio button values in a PHP/MySQL application, I've noticed a variety of approaches. I'm curious to know which method is considered more effective and why. The scenario involves a typical Yes/No question with ...

Items that do not appear once my page has finished loading

We are developing an admin panel for the client to manage updates on their own website. To achieve this, we are using JavaScript and PHP (ajax) to create divs: $(document).ready(function($) { function loadContent(page) { ...