Modifying an image's height and width attributes with jQuery and CSS on click action

I'm currently developing a basic gallery using HTML, CSS, and jQuery. The objective is to have a larger version of an image display in a frame with an overlay when the user clicks on it. While this works flawlessly for horizontally-oriented images, vertical images appear distorted in the larger view.

You can check out a live sample of my project on CodePen: http://codepen.io/anfperez/pen/AXZgRV

I attempted to modify the attributes of the larger image by storing its height in a variable and then updating the attribute using jQuery, but unfortunately, it hasn't been successful.

How can I retrieve the height and width of the larger image URL and insert them into the frame? Below is the code snippet I tried that didn't yield the desired outcome:


var height_large = $(this).attr('height')
var width_large = $(this).attr('width')

$('#frame img').attr('height', height_large)
$('#frame img').attr('width', width_large)

Here is the direct link to the photo I am attempting to fetch:

Answer №1

By setting the height to auto for the #frame img, I was able to achieve the desired result. This approach allows the larger image to be displayed with a fixed width while adjusting the height accordingly for proportional rendering. It is important to ensure that your images are at least as wide as the fixed width to prevent upscaling.

#frame img {
  display: none; 
  position: fixed;
  background-color: white;
  width: 700px;
  height: auto;
  margin-left: -350px;
  left: 50%;
}

Answer №2

Once you have set the src in the frame, you can access the image's naturalWidth and naturalHeight properties and use them to define the CSS width and height respectively. To ensure that these values are applied after the image finishes loading, it is recommended to add a load event listener on the frame image element. Additionally, adjusting the marginLeft property to half of the image's width can effectively re-center the image. Introducing a fade effect for the frame/overlay transition can enhance the visual experience when swapping images:

$('#frame img').on('load', function(e) {
  e.target.style.width = e.target.naturalWidth + 'px';
  e.target.style.height = e.target.naturalHeight + 'px';
  e.target.style.marginLeft = -(e.target.naturalWidth / 2) + 'px'; //re-center the image
  $(this).fadeIn(); 
  $('#overlay').fadeIn();
});

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

Iterating through object using jQuery

I'm facing an issue with iterating through a JSON object for the first time. The JSON is structured like this: { "response": { "2012-01-01": { "Available": 99, "Variations": [ { ...

Facing an error response with the Javascript callout policy in Apigee. Any suggestions on fixing this issue?

This is the code snippet I'm using in my JavaScript callout policy var payload = JSON.parse(request.content); var headers = {'Content-Type' : 'application/json'}; var url = 'https://jsonplaceholder.typicode.com/posts'; va ...

Learn the process of extracting various data from a PHP source and saving it in select options through AJAX

One of the features on my website is a select option that allows users to choose a hotel name obtained from a dynamic php script. Once a hotel is selected, another select option displays room types available based on the chosen hotel. However, there seem ...

Turn off the scroll function while loading a webpage

Here is the script for my preloader: $(window).load(function() { $("#loading").fadeOut(1000); I want to prevent scrolling while the "loading" is still visible, and then enable it again after the fade out completes. ...

Adaptable Image Maintains Integrity

My code is generating the following output: While I want the images to resize when dragged in, one of the right-hand images does not move below the main image as intended. Here is my code: Can anyone help me resolve this issue? Check out my CSS and HTML ...

Is it possible to include a shared helper text for two textfields that have been imported from MUI in a React.js project?

This snippet contains the code for my password container: .password-form-container { width: 85%; height: 7%; position: relative; top: 230px; left: 40px; display: flex; justify-content: space-between; border: 1px solid red; } <div clas ...

The steps to display a partial view within another view in React Native

Attempting to show the View after calling alert("Hi") in the renderMoreView function has been challenging for me. The alert works fine, but displaying the View is where I am encountering issues. class Main extends Component { state = { moreButton: f ...

Activate the div when hovering over the span

Experiencing an issue with triggering a visible div while hovering over a span. Here is the code structure: <ul class="products"> <li> <a href="somelink"> <img src="some image"> <div class="overlay"> Some Text</div> & ...

Developing an interactive web interface with HTML

I've been attempting to design a flexible HTML page that replicates the layout of a Java applet clock, but I'm unsure if my current approach is correct. Below is an example of the three-clock image set that I am currently working on. My method i ...

The dichotomy between public and private methods within a Vue.js component

Within a component, I have two functions defined. One is foo(), which is defined within <script>, and the other is fooExported(), which is defined in the body of export default {}. My understanding is that functions inside export default {} can be a ...

Utilizing a single slider for multiple divs: Merging three separate functions into one jQuery function

I have a website showcasing 3 different "draws", each containing full-screen images. Currently, I have separate functions and sliders for each draw, but I want to combine them into one function and slider that navigates through the images of the displayed ...

Issue with Lazy Loading in Angular 4 Universal

I recently created a new Angular CLI project to delve into server-side rendering with Angular Universal. Everything was set up and running smoothly, until I decided to implement lazy-loading for a module named 'lazy'. After implementing lazy-lo ...

Using a static function within a library's state function in NextJS is throwing an error: "not a function"

Inside a library, there's a special class known as MyClass. This class contains a static method named setData. The contents of the MyClass.js file are shown below: class MyClass { static DATA = ''; static setData(data) { MyClass ...

What is an alternative method to retrieve form data without relying on bodyParser?

When it comes to accessing posted form data without using bodyParser, what alternatives are available? How exactly does bodyParser grant access to the data in req.body? Additionally, I am curious about the inner workings of this process on a deeper level. ...

"Unlocking the secret to fetching the id of the clicked element within a Highchart context menu

Is it possible to retrieve the id of a clicked button on the highchart context menu? Alternatively, is there a way to execute the click function twice? const contextButtonArray = []; contextButtonArray.push({ { text: 'TEST BUTTON&ap ...

It is not possible to decrease the size of the image that is currently used as the background image

Three images are arranged in this manner: https://i.stack.imgur.com/u4PdK.png The HTML code for this setup is as follows: <div class="lb-controlContainer"> <div class="lb-closeContainer"> <a class="lb-close"&g ...

Utilize the "incorporate" feature to include any string within an array

I am currently working on improving the search function in my application. This particular search function takes input from a search bar and is designed to handle multiple search terms. For example, it should be able to handle queries like "javascript reac ...

What is the best way to create a repeating Jquery loop in code?

Hey there! I've been working on creating a button that toggles the background color from white to yellow and back again using Jquery. However, I've hit a bit of a roadblock with implementing a loop function. If you'd like to take a look at m ...

The re-rendering of a functional component utilizing React.useCallback and React.memo() is occurring

I was delving into React concepts and eager to experiment with some new things. Here are a few questions that crossed my mind: Does every functional child component re-render when the parent state changes, even if it doesn't have any props? It seems ...

A straightforward interval-based Ajax request

I've recently delved into the world of Ajax and jQuery. Just yesterday, I embarked on creating a simple ajax request for a form that sends a select list value to a PHP script and retrieves data from a database. Things are going smoothly so far! Howev ...