Adjust image size as the page is resized

My challenge is to resize images that are typically too large for the current window size, ensuring they fit within 85% of the client window. I tried creating a function utilizing onload and onresize events but encountered issues.

function adjustImages(){
    var images = document.getElementsByTagName("img");
    var goodWidth = document.body.clientWidth * 0.85;
    
    for(var i=0; i < images.length; i++){
        images[i].maxWidth = images[i].width;
        
        if(images[i].width > goodWidth){
            images[i].width = goodWidth;
        }
        
        if((images[i].width < images[i].maxWidth) && (images[i].width < goodWidth)){
            images[i].width = goodWidth;
        }
    }
}

I apologize for the confusion in my earlier explanation. Let me clarify with an example: Suppose we have images with sizes like 1920x1080, 1280x720, and 640x480. All these images should be resized to fit no more than 85% of the browser window size. Here's how it should work:

For a resolution of 1680x1050:
Image 1: (1680 * 0.85) x (1050 * 0.85);
Image 2: 1280x720;
Image 3: 640x480;

For a resolution of 800x600:
Image 1: (1680 * 0.85) x (1050 * 0.85);
Image 2: (1280 * 0.85) x (720 * 0.85);
Image 3: 640x480;

When the resolution increases back to 1680x1050:
Image 1: (1680 * 0.85) x (1050 * 0.85);
Image 2: 1280x720;
Image 3: 640x480;

Answer №1

Perhaps utilizing HTML and CSS exclusively could be a more suitable solution instead of resorting to Javascript.

For instance

   <img width="85%" src="http://upload.wikimedia.org/wikipedia/commons/3/36/Hopetoun_falls.jpg" />

Answer №2

It appears that the text you provided is not a direct copy and paste, as it contains an error with using "and" instead of "&" or "&&", and lacks proper statement termination.

By making these adjustments:

function a() {
    var img = document.getElementsByTagName("img");
    var goodWidth = document.body.clientWidth * 0.85;
    for (i=0; i < img.length; i++) {
        img[i].maxWidth = img[i].width;
        if(img[i].width > goodWidth){
            img[i].width = goodWidth;
        }
        if((img[i].width < img[i].maxWidth) && (img[i].width < goodWidth)) {
            img[i].width = goodWidth;
        }
    }
}

This code snippet fulfills your requirements.

Furthermore, it might be advisable to convert the value of `goodWidth` to an integer using parseInt to ensure accurate comparisons.

var goodWidth = parseInt(document.body.clientWidth * 0.85);

Lastly, I recommend utilizing jQuery for its efficiency and versatility in web development tasks.

Answer №3

If you're looking for a reliable way to determine the user's browser width (or height) after the body has finished loading, I suggest utilizing jQuery's $(window).width() method. This approach is compatible across all browsers and provides accurate results.

Below is a conceptual function that you can use:

(function(){
    var browserWidth = $(window).width();
    var images = document.getElementsByTagName("img");
    var adjustedWidth = browserWidth * 0.85;
    for(var i=0; i<images.length; i++){
        var oldImgWidth = images[i].width;
        if (oldWidth >= browserWidth){
            images[i].width = adjustedWidth;
            //Remember to adjust the image height proportionally
            images[i].height *= adjustedWidth / oldImgWidth;
        }
    }
}());

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

Guide on displaying the appropriate child "div" with jQuery?

I am facing a challenge with my two dependent dropdowns that toggle the visibility of divs based on user input. The first div is functioning correctly, however, every time the user makes a selection in the second div, it impacts the first div. $(docume ...

Execute a function on elements that are added dynamically

I'm in the early stages of learning javascript and jquery, so this issue might be very basic. Please bear with me. Currently, I am dynamically adding new link (a) elements to a division with the id "whatever" using the following code: $("#whatever") ...

Grouping emitted events using RxJS in a Node.js environment

Currently, I am interfacing with a database and receiving the results in a continuous stream of events labeled 'db_row_received'. My aim is to categorize these results based on the company Id, however, I am encountering an issue where the subscri ...

Is it necessary to compile Jade templates only once?

I'm new to exploring jade in conjunction with express.js and I'm on a quest to fully understand jade. Here's my query: Express mentions caching jade in production - but how exactly does this process unfold? Given that the output is continge ...

Show an image in JPEG format using JavaScript within an img tag

Suppose http://example.com/image returns unique image data in response headers and the image itself. Each request to http://example.com/image generates a different image that is not related to the request itself. Besides the image, additional information s ...

Navigating through nested JSON arrays in JavaScript involves looping through multiple dimensions

I am facing difficulty finding the correct solution to my issue here. I am trying to iterate through the nested Products arrays in order to display each Product name. Can this be achieved with my current code, or should I consider rewriting it to make qu ...

Is there a way to refresh a webpage on an express route and display an error message at the same time?

I'm currently in the process of building a basic website that includes features for user login and logout. This functionality is based on a local JSON file containing a list of users and their hashed passwords. My server setup involves using express s ...

NextJS middleware API receives an uploaded image file form, but the request is undefined

Currently, I'm utilizing NextJS to handle form data processing and database uploads, with a pit stop at the NextJS API middleware for image editing. pages/uploadImage.tsx This is the client-side code handler. ... async function handleImageUpload(imag ...

What is the most effective way to set up HTTPS for handling all connections in Node.js?

In my project to create a stateless authentication system using Double Submit Cookie in Node.js/ExpressJs, I am exploring ways to ensure all connections are made over HTTPS. My goal is to optimize for handling high traffic while also prioritizing security ...

Disregarding NPM dependencies for individual packages

I need to include a package (d3.js) in my project's package.json. However, when I run npm install, I do not want npm to install any dependencies related to d3.js or run any install scripts for it. Essentially, I want npm to only fetch and unpack the p ...

Is JSON Compatible with the Switch Statement?

Could someone help me with creating a switch statement in JSON? {"Errors":{"key1":"afkafk"},"IsValid":false,"SuccessMessage":""} I attempted to use: switch(response) { case response.Errors.key1: alert('test'); default: } However, t ...

Incorporating an express server into the vue-webpack-boilerplate for enhanced functionality

Recently, I got my hands on the vue-webpack-boilerplate from GitHub, and so far, it seems pretty impressive! This is my first time working with webpack and ESlint, so I'm eager to learn more. However, I have a question about integrating an express ba ...

Is there a way to efficiently import multiple Vue plugins in a loop without the need to manually type out each file individually?

I am looking for a way to streamline this code by using a loop to dynamically import all .js files from a specified directory (in this case, the 'plugins' directory). const plugins = ['AlertPlugin', 'AxiosPlugin', 'Confi ...

Is it possible in HTML to detect *any* changes made to an input, not just those made by the keyboard?

Let's consider a scenario where we have an input element like this: <input id="myInput" type="text" /> The question now arises, how can we detect when the value of this input is changed programmatically (such as through $("#myInput").val("new ...

"Enhance your listening experience with an audio player featuring album covers as captivating

Is there a way to create an audio player with the album cover image serving as the background, while ensuring all control buttons are displayed on top of that same image? I attempted using the following code snippet: <audio controls = 'controls&ap ...

"Transferring a JavaScript variable to Twig: A step-by-step guide for this specific scenario

When it comes to loading a CSS file based on the user's selected theme, I encountered an issue while trying to implement this in my Symfony application using Twig templates. The code worked flawlessly on a simple HTML page, but transferring it to a Tw ...

Avoid using fs.read without returning a value to console.log

Seeking assistance with parsing a text file named information.txt and displaying the values using console.log. Here is the code snippet: fs.readFileSync("information.txt", "utf-8", function (err, data) { ...

What could be causing my Express API registration route to fail when attempting to POST?

Currently, I'm in the process of developing a compact authentication system for a practice project that I've undertaken. As part of this endeavor, I am sending POST requests via Postman to my Express server located at http://localhost:4000/api/re ...

What steps should I take to turn off caching specifically for directory listings?

Is there a way to generate a fresh file list every time without using cached data? I have a basic PHP script that fetches the contents of a directory and stores them in an array. The script works perfectly the first time it is used, but subsequent calls m ...

How to efficiently upload multiple files simultaneously in Angular 10 and .NET Core 5 by utilizing a JSON object

I have a JSON object structured like this: Class->Students this is a basic representation of my TypeScript class export class Classroom { Id:number; Name:string; Students:Student[]=[]; } export class Student { Name:string; Age:number; Sex:string; Imag ...