What is the best way to adjust the size of an image to the viewing area

In my application, users can take photos either horizontally or vertically. These images are then displayed in a gallery on a webpage, and when clicked on, they expand using a Modal.

My issue arises with horizontal images looking smaller than vertical ones due to the CSS property max-width: 30vw. How can I adjust the width of horizontal images without affecting vertical ones?

Since the images are dynamic, assigning specific widths through classes is not an option.

This is the current CSS for the images:

.modal-content{
    margin: auto;
    display: block;
    width: 100%;
    max-width: 30vw;
    max-height:85vh;
    object-fit: cover;
}

And this is the setup for the modal:

<div id="myModal" class="modal">
  <a class="btn btn-primary" id="btnDownload" download><i class="fa fa-download"></i> Download</a>
  <span class="close">&times;</span>
  <img class="modal-content" id="img01">
</div>

Here is a Vertical image example:

https://i.sstatic.net/va1EP.png

And here is a Horizontal image:

https://i.sstatic.net/y3SDw.png

This is the Javascript function I am using:

function AgrandaOpenModalr(img) {
    var modal = document.getElementById("myModal");

    // Insert the clicked image into the modal
    var modalImg = document.getElementById("img01");
    var captionText = document.getElementById("caption");
    var btnDownload = document.getElementById('btnDownload');

    modal.style.display = "block";
    modalImg.src = img.src;
    captionText.innerHTML = " ";
    btnDownload.href = img.src;
    
    // Close the modal when clicking on 'x'
    var span = document.getElementsByClassName("close")[0];
    span.onclick = function () {
        modal.style.display = "none";
    }
}

Answer №1

It seems that the same model is always loaded, but the src changes dynamically when the modal opens to correspond with the correct picture. Is that how it operates?

You mentioned that you are unable to work with an additional class, correct?

Perhaps a potential solution would be to invoke a JavaScript function when the modal is displayed? This could involve utilizing an event listener or attaching an onclick event.

Upon executing the following function, it adjusts the max-width of the image accordingly.

// The method call to be performed when the modal opens
setModalWidth();

// Function to adjust the maxWidth as needed
function setModalWidth() {
   let img = document.querySelector('.modal-content');

   if(img.naturalWidth > img.naturalHeight){
      img.style.maxWidth = '50vw';
   } else {
      img.style.maxWidth = '30vw';
   }
}

EDIT

The specific method suggested above should suffice, but considering the script you've already implemented, you can also integrate the code into that function.

Allow me to illustrate

function AgrandaOpenModalr(img) {
    var modal = document.getElementById("myModal");

    // Retrieve the image and place it within the modal - utilizing its "alt" text as a caption
    var modalImg = document.getElementById("img01");
    var captionText = document.getElementById("caption");
    var btnDownload = document.getElementById('btnDownload');

    modal.style.display = "block";
    modalImg.src = img.src;
    
    // Addition of if-statement for adjusting max-width    
    if(modalImg.naturalWidth > modalImg.naturalHeight){
      modalImg.style.maxWidth = '50vw';
    } else {
      modalImg.style.maxWidth = '30vw';
    }

    captionText.innerHTML = " ";
    btnDownload.href = img.src;
    
    // Obtain the <span> element responsible for closing the modal
    var span = document.getElementsByClassName("close")[0];

    // Upon clicking on the <span> (x), close the modal
    span.onclick = function () {
        modal.style.display = "none";
    }
}

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

Discover the effective method in Angular to display a solitary password validation message while dealing with numerous ones

Here is the pattern we use to validate input fields: The length of the input field should be between 6 and 15 characters. It should contain at least one lowercase letter (a-z). It should contain at least one uppercase letter (A-Z). It should contain at le ...

Utilizing styled-components or personalized components alongside cypress

Cypress selector made simple: just use cy.get('.myComp') and it will select <input className="myComp" />. But when it comes to styled-components... Perhaps we have to resort to using custom attributes like cy-data or cy-testid. Sadly, it s ...

Find the months where two date ranges overlap with the help of date-fns

Is there a way to find the overlapping months between two date intervals using date-fns? const range1 = { start: new Date('2018-01-01'), end: new Date('2019-01-01') } const range2 = { start: new Date('2018-07-03'), end: new D ...

Issue with Codeigniter's AJAX functionality causing div reloading to not function as intended

I am currently facing an issue where I can display text directly from the database on a webpage. However, when I edit the text in the database, I want it to automatically reload and show the updated text without having to refresh the entire page. Unfortun ...

Sending a POST request in nodeJs that does not return any value

I have a button on my client site that sends a POST request to my server. The request does not require a response as it simply inserts data into the database. However, after clicking the button, the client continues to wait for a response until it times ou ...

Juggling PHP scripts within javascript

Can you help me with a question I have? I am working on multiple JS scripts, such as this one: <script> $('#mapveto1').click(function() { $('#mapveto1').addClass('banned'); $('#map1').text('cobble ...

Vue.js - Leveraging arrays in functions for efficient iteration

I need help using a JS array in a Vue.js function for looping. Here is the code I tried: Vue: computed: { bbb: function(){ var vvv=this.Preused.length-this.quote.lines.length; let added_products=[]; if(vvv > 0){ for(var i = 0; i <= vvv-1 ...

Is there a CSS4 resolution for transitioning from 0 to auto?

I searched extensively for information on CSS4, but unfortunately I came up empty-handed. Back in the era of CSS3, a common challenge arose when it came to height transitions from 0 to auto without relying on JavaScript. The introduction of transitions sa ...

What steps are involved in extracting a Flot animation?

Check out this cool animation of a diatomic chain in action on this website: http://lampx.tugraz.at/~hadley/ss1/phonons/1d/1d2m.php I'm interested in extracting it, specifically to create a gif. The HTML script for the animation is visible: var c= ...

Ensuring data integrity within table rows using Angular to validate inputs

I am using a library called angular-tablesort to generate tables on my webpage. Each row in the table is editable, so when editMode is enabled, I display input fields in each column of the row. Some of these input fields are required, and I want to indica ...

I am looking to utilize React and Next.js to map my array from an object. The component is a function employing hooks

I am attempting to map an array within an object and encountering some challenges. The structure of the object is as follows: const data = {data: (6) [{…}, {…}, {…}, {…}, {…}, {…}], page: 2, per_page: 6, total: 12, total_pages: 2} I have been ...

Dead keyup event using jQuery live in SignalR invocation

I am working on a sample chat application using SignalR, but I'm facing an issue with my keyup event not functioning properly. Below is the code snippet: // Keyup event for text box $(".ChatText").on('keyup', function () { if($(".ChatTe ...

How can I use JavaScript and HTML to print a canvas that is not within the print boundaries?

As someone who is new to javascript, I recently created a canvas function that allows me to successfully print. However, I am encountering an issue with printing large canvas areas. When I navigate to the further regions of the canvas and try to print, i ...

Mobile-style menu with full desktop height

I am currently working on developing my first custom WordPress theme from scratch. My goal is to design a mobile-style menu that can also be displayed on desktop screens. To achieve this, I have used jQuery to implement the sliding effect. You can view a ...

Can you explain the contrast between 'depict' and 'examine' when using Jest?

I am currently diving into the world of unit testing in Vue.js with Jest. One question that keeps popping up is when to use describe and when to use test ? TodoApp.vue Component : <template> <div> <h1>TodoApp Componenent</h1> ...

How can you connect a property to the output of a method in Vue.js when working with TypeScript and vue-property-decorator?

I'm working with a TypeScript single file vue component. I've encountered an issue where the template does not display the values returned by certain component methods. Here's a snippet of the template: <div class="order-items"> ...

Can the image upload file size be customized or adjusted?

Recently, I've come across a standard input file code that looks like this: <Label class="custom-file-upload"> <input type="file" onChange={onDrop} /> Upload Photo </Label> I have been thinking about limiting the size of the ...

Could not locate the CSS file within the HTML document (404)

I've searched high and low on YouTube but can't seem to find a solution to this problem. Every time I run the code, it gives me an error message saying GET net::ERR_ABORTED 404 (NOT FOUND) <html> <head> <title>itays websit ...

monitoring the HTML code post-editing

After using jQuery, I made modifications to the HTML source code by adding several text fields. However, when I check the page source in Google Chrome, it still shows the original source code. Is there a method to view the updated HTML code? ...

Issue with ng-click directive not triggering within an Ionic tag unless using interpolation

When attempting to pass a value to a function on ng-click, I noticed that it works outside of the ionic tag without interpolation. However, I am confused as to why I need to interpolate it within the ionic tag. Here is a sample of the code: <span ng-cl ...