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

Unable to redirect to the initial page successfully

My React application is using Redux-Toolkit (RTK) Query for user login functionality. When the user clicks the "logout" button, it should redirect to the home page ("/"). However, I'm facing an issue where clicking the "logout" button does not trigger ...

where should the arguments for the postMessage command be directed within the YouTube iframe?

Apologies if it seems like I'm reposting a similar issue, but this is actually a different problem with a unique approach. Currently, I have an iframe element: <iframe id="video1" width="970" height="546" src="https://youtube.com/embed/9IYRC7g2IC ...

Converting Javascript tools into Typescript

I'm currently in the process of migrating my Ionic1 project to Ionic2, and it's been quite an interesting journey so far! One challenge that I'm facing is how to transfer a lengthy list of utility functions written in JavaScript, like CmToFe ...

Z-index creates an obstacle that prevents items from being clicked on

I am facing an issue with my container div that has an inset drop shadow applied to it. Inside this container, I have child elements and I want these children to be clickable. For the drop shadow to show, it is necessary to set the z-index of the child el ...

What are some methods for concealing custom CSS overflow in IE8?

In my latest project, I created a script that utilizes pure css to toggle between an image, image caption, and text. However, when testing it in IE8, all the elements appear at once instead of toggling as intended. To showcase the issue more clearly, I h ...

Ensure that you do not display the result until all Ajax calls have finished processing

When faced with a challenging problem, I persist through multiple attempts and seek your assistance in finding a solution. My current goal is to populate a table with the number of viewers for a specific streamer using the Twitch API. To achieve this, I ...

Steps to display a modal within an inactive tab:

I have been using ngx-bootstrap tabset, although I believe this issue could apply to all bootstrap tabs as well. <tabset> <tab class='active'> <angular-modal-component> </angular-modal-component> </tab> <tab> & ...

Achieve this effect by making sure that when a user scrolls on their browser, 50% of the content is entered into view and the remaining 50%

Is there a way to achieve this effect? Specifically, when the user scrolls in the browser, 50% of the content is displayed at the top and the other 50% is shown at the bottom. ...

Dynamic resizing of Bootstrap Carousel

As I delve into the realm of web design, I've encountered a puzzling issue with my BootStrap Carousel on a website project. Despite copying the code directly from the BootStrap 5.1 carousel documentation page, its behavior is rather odd, and I'm ...

Is it possible to reverse the use of JQuery's .each() function without any additional plugins or modifications?

Similar Question: Reversing JQuery .each() Is there a better approach to using .each() in reverse? Currently, I am implementing it like this: var temp = []; $("#nav a").each(function() { temp.push($(this)); }); temp.reverse(); for(var i = 0; i ...

Displaying fresh data from a JSON URL by clicking on a button and dynamically refreshing the view in

Apologies if this question has been asked before, but I couldn't locate it. I’m currently engaged in an Angular project where I’ve loaded an external JSON file using http. The data is presented through ngRepeat. When a button is clicked, I aim t ...

Issue with managing timezones in Angular with CDT/CST offsets

I have a date in UTC format that I need to convert to CST. It is 5 hours ahead of UTC during CDT and 6 hours ahead during CTC. The UTC date is '2016-09-07T05:00:00Z' <body> <div ng-app="myApp" ng-controller="datCtrl"> <p>Da ...

Transform a Microsoft Word table into HTML code

My boss has provided me with a very detailed table in an MS Word document filled with various colors, shapes, and lots of information that I need to incorporate into a website. I attempted saving the Word file as HTML and then transferring the code over, ...

What steps can I take to convert my React class into a function in order to incorporate Material UI components effectively?

With Emailjs set up successfully, my next step is integrating Material UI text fields (link: https://material-ui.com/components/text-fields/#text-field) to enhance the design of my project. The challenge I'm facing is incorporating Material UI classe ...

Is there a way to prevent my jQuery from triggering the <a href> unless the ajax post is successful?

I am attempting to update the database and redirect the user's browser to a new page with just one click. Here is how the HTML appears: <a id='updateLiveProgress' style='width:118px;' href='~link~'>Click here</ ...

A technique for calculating the total quantity of each item individually while using v-for in VueJS

Struggling to code (complete newbie) using VueJS and facing a major roadblock. I have a list of orders and I need to sum the quantities of each item separately. The only way to access the items is through v-for. <tr> <td data-th="list"> < ...

Enhancing table field functionality in Backbone.js

In my Backbone application, I am trying to debug the following code outline. window.TableView = Backbone.View.extend({ initialize: function() {... .. .. ... }); }, selectRow: function() { ... ... .. }, render: function() { // ...

Troubleshooting: Issues with AngularJS Data Binding in HTML Tables

I have been working on code from an online tutorial but unfortunately, it is not functioning properly. I have checked the script, app, and controller but still cannot identify the issue. Any assistance would be greatly appreciated! ...

The status value in the result has a whitespace just before the term "success"

Apologies for the unclear question, but I encountered a strange bug in my code. I am trying to show an alert to users informing them that the updates have been successfully completed. Below is the code snippet containing an if() block where the alert shoul ...

Troubleshooting: jQuery Orientation Change Issue Unresolved

Below is the code snippet I am using: jQuery(window).on("orientationchange",function(){ var maxHeight = -1; jQuery('.article .articleHead').each(function() { maxHeight = maxHeight > jQuery(this).height() ? maxHeight : jQuery(this). ...