jQuery image resizing for elements

I have successfully adjusted the images in the gallery to display one per row for horizontal orientation and two per row for vertical orientation.

Now, I am facing a challenge in making the images scalable so they can resize dynamically with the window. Any suggestions on how to achieve this?

Below is the code snippet:

var gallery = new Gallery($('#gallery_images_inner'));

function Gallery(selector){

this.add_module = function(type, image){
    var container = $('<div />' , {
        'class' : 'gallery_container'
    }).append(image);
    if(type == 'horizontal'){
        var h_ar = image.attr('height') / image.attr('width');
        container.css({
            'width' : selector.width(),
            'height' : selector.width()*h_ar
        })
    }
    if(type == 'vertical'){
        container.css({
            'width' : v_width,
            'height' : v_height
        })
    }
    container.appendTo(selector);
    container.children('img').fitToBox();
}
var _this = this;
var gutter = 0;
// initializing variables for counting vertical images
var v_counter = 0;
var w_pxls = 0;
var h_pxls = 0;
// looping through images to identify vertical ones
selector.children('img').each(function(){
    if($(this).attr('width') < $(this).attr('height')){
        v_counter++;
        h_pxls += $(this).attr('height');
        w_pxls += $(this).attr('width');
    }
})
// calculating average aspect ratio for vertical images (any deviations will be cropped)
var h_avrg = Math.floor(h_pxls/v_counter);
var w_avrg = Math.floor(w_pxls/v_counter);
var v_ar = h_avrg/w_avrg;
var v_width = (selector.width())/2;
var v_height = v_width*v_ar;
selector.children('img').each(function(){
    if(parseInt($(this).attr('width')) > parseInt($(this).attr('height'))){
        _this.add_module('horizontal', $(this));
    }else{
        _this.add_module('vertical', $(this));
    }
})
selector.isotope({
    masonry: {
        columnWidth: selector.width() / 2
    }
});

}

Answer №1

Employ percentages for the container that holds the image, adjusting both its width and height accordingly. Additionally, apply a percentage value to the image's width and height relative to its container, ensuring it is proportional.

Answer №2

CSS would be a more effective solution for this issue. By simply setting the image width to 100%, it will automatically adjust its size according to its parent container. In the provided example, the .container occupies 25% of the window and the image fills up 100% of that space. You can use tools like firebug to experiment with changing the width of the container and observe the impact.

<DOCTYPE html>
<html>
<head>
    <style>
        .container {
            width: 25%;
        }
        .container img {
            width: 100%;
        }
    </style>
</head>
<body>

    <div class="container">
        <img src="http://ldlocal.web44.net/test2/img/gallery0.jpg">
    </div>

</body>
</html>

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

Using [(ngModel)] in Angular does not capture changes made to input values by JavaScript

I have developed a custom input called formControl, which requires me to fetch and set its value using [(ngModel)]: import { Component, Injector, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, FormControl, NG_VALUE_ACCE ...

Adjust the value of a JavaScript variable using Selenium

My dilemma involves a boolean JavaScript variable called foo, which is currently set to true but I need it changed to false. This particular variable has the advantage of having global scope. When using Selenium, what is the most effective method for alte ...

Can you explain the distinction between [att|=val] and [att~=val] in css?

Could someone help me differentiate between the [att|=val] and [att~=val] attributes in CSS? I'm having trouble grasping the concept. Thank you! ...

Using Vue to display a Div inside a TD element of a table does not result in a reactive behavior

I am encountering an issue with a table where the last column contains a div with three options (View, Edit, and Delete). This submenu is initially hidden, but when clicking on the options button in the last column of the table, the array used to control i ...

Switch out multiline text with javascript

Could someone assist me with this question? I am attempting to locate and replace specific code within a JavaScript file. The code is included in an AJAX response that contains a significant amount of HTML code. After retrieving the AJAX response, I stor ...

ng-if directive does not show data in AngularJS

I have a dynamic collection of images and videos that I want to display one at a time. Specifically, when I click on an image ID, I want it to show the corresponding image, and when I click on a video ID, I want it to show the relevant video. Below is the ...

Ensure that the height of the content in JQuery Mobile is set to 100

I'm currently working on an app using JQuery Mobile. Check out this link for my HTML code. There's a full-screen <iframe> within my page. Even though I've specified width:100%; height:100%; border:0% for the iframe, it ends up being ...

Encountering a MiniCssExtractPlugin error while trying to build with npm

I have encountered an issue while trying to execute "Npm Run Build" on my reactjs website. The error message I keep receiving is as follows: /usr/local/lib/node_modules/react-scripts/config/webpack.config.js:664 new MiniCssExtractPlugin({ ^ TypeErr ...

AngularJS 2: Updating variable in parent component using Router

My current app.component looks like the following: import { Component, Input } from '@angular/core'; import {AuthTokenService} from './auth-token.service'; @Component({ selector: 'app-root', templateUrl: './app ...

Troubleshooting issues with ng-options not correctly updating ng-model in AngularJS when using ajax requests

I have a question regarding my logic that I can't seem to figure out. In this Fiddle example, everything works fine without using AJAX or a timeout. However, when I try to implement the same logic with a timeout/ajax, the expected behavior does not o ...

Employing setTimeout within a repetitive sequence

function displayColors() { $.each(colors, function(index) { setTimeout(function(){ revealColor(colors[index]); }, 1000); }); } I'm attempting to create a loop where the revealColor function is executed every second until all colors ...

When hovering, apply style 1 to all elements with the same id, and style 2 to the hovered element

I'm working with some user-generated divs that I want to dynamically highlight when hovered over, while simultaneously blurring the other divs. My challenge is figuring out how to change the style of the hovered div separately from all the others. Th ...

The issue with Angular's mat-icon not displaying SVGs masked is currently being investigated

I have a collection of .svgs that I exported from Sketch (refer to the sample below). These icons are registered in the MatIconRegistry and displayed using the mat-icon component. However, I've observed issues with icons that utilize masks in Sketch ...

How to handle multiple file uploads and save information in dual tables using Laravel

Currently, I am dealing with a <form> that allows users to upload multiple files. However, my requirement is to store these uploaded files in a separate table within the database. Unfortunately, the files are not being saved into the database for som ...

A layout featuring a grid design that includes spacing and gutters between items, however, there is no spacing between the items

I am looking to create a grid layout where each child element represents an individual grid square. However, I am facing an issue with spacing between the children and the parent container, which is not desired. How can I eliminate this unwanted space? U ...

Can Chrome Support Bookmarklets?

While attempting to craft a bookmarklet in Chrome using the console, I encountered the following error: Refused to load the script 'https://code.jquery.com/jquery-1.6.1.min.js' because it violates the following Content Security Policy directive: ...

Unable to trigger JQuery .blur event

I am currently working on implementing server-side validation for an input field that needs to be validated when it loses focus. However, I'm running into an issue where the alert is not triggered when the input field loses focus. Here's a snipp ...

Only JSON objects with a boolean value of true will be returned

I am working on returning JSON objects in JavaScript/TypeScript that have a true boolean value for the "team" property. For example, the JSON data I am using is as follows: { "state": "Texas", "stateId": 1, "team": true }, { "state": "Cali ...

Implementing jqury.datatable to display an empty table

I am utilizing jquery.dataTables.js to display my table data. However, upon initial load, I prefer to have an empty table and only load data after selecting certain filters. Even though I use iDeferLoading, it still requires some initial data to load, but ...

Is there a way to initiate the server only after webpack has finished bundling all of the bundles

"scripts": { "start": "node server.js", "build": "webpack" }, Is there a way to execute both npm run build and npm start with a single command? "scripts": { "start": " ...