Tips for centrally zooming responsive images without altering their dimensions

I have created a custom jQuery and CSS function that allows an image to zoom in and out on mouseover while maintaining a constant box size. I modified an example code to suit my needs.

Check out the demo here: https://jsfiddle.net/2fken8Lg/1/

Here is the code:

JavaScript:

 $('.zoom img').on({
   mouseover: function() {
     var $scale = 1.5;
     if (!$(this).data('w')) {
       var $w = $(this).width();
       var $h = $(this).height();
       $(this).data('w', $w).data('h', $h);
     }
     $(this).stop(true).animate({
       width: $(this).data('w') * $scale,
       height: $(this).data('h') * $scale,
       left: -$(this).data('w') * ($scale - 1) / 2,
       top: -$(this).data('h') * ($scale - 1) / 2
     }, 'fast');
   },
   mouseout: function() {
     $(this).stop(true).animate({
       width: $(this).data('w'),
       height: $(this).data('h'),
       left: 0,
       top: 0
     }, 'fast');
   }
 });

CSS:

.zoom {
  position: relative;
  float: left;
  margin: 30px 0 0 30px;
  width: 400px;
  height: 180px;
  overflow: hidden;
  border: 1px solid #000;
}

img {
  position: absolute;
  width: 400px;
  height: 180px;
}

HTML:

<div class="zoom">
  <img src="https://www.lamborghini.com/en-en/sites/en-en/files/DAM/it/models_gateway/blocks/special.png">
</div>

This code works well with fixed image sizes, but I'm wondering how I can make it work with responsive images. My website is designed to be fully responsive, so having fixed CSS widths or heights will not work across different browser sizes. Is there a way to achieve this with responsive images, perhaps without relying solely on CSS?

Answer №1

To achieve a zoomed-center look without compromising responsiveness, using transforms in CSS is the recommended approach. This solution was suggested by user @Keith and can be seen in action through the following JS fiddle example.

Check out the demo here: https://jsfiddle.net/2fken8Lg/2/

Here's the HTML code:

<div class="zoom">
  <img src="https://www.lamborghini.com/en-en/sites/en-en/files/DAM/it/models_gateway/blocks/special.png">
</div>

And the corresponding CSS:

.zoom {
  position: relative;
  border: 1px solid #333;
  overflow: hidden;
  width: 100%;
}
.zoom img {
  max-width: 100%;

  -moz-transition: all 0.3s;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
}
.zoom:hover img {
  -moz-transform: scale(1.1);
  -webkit-transform: scale(1.1);
  transform: scale(1.1);
}

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

The value of the comment box with the ID $(CommentBoxId) is not being captured

When a user enters data in the comment box and clicks the corresponding submit button, I am successfully passing id, CompanyId, WorkId, and CommentBoxId to the code behind to update the record. However, I am encountering an issue as I also want to pass the ...

The Problem of Restoring Column Height in Tabulator 4.6.3 Filters

The Issue After activating and deactivating header filters, the column height does not return to its original state. Is this the expected behavior? Is there a way to reset the column height? Check out this JS Fiddle example: https://jsfiddle.net/birukt ...

Adjusting HTML image sizes

How can I prevent large images from extending off the edge of the screen when using HTML img tags? Is there a way to scale them to fit within the browser window or specify a set percentage for their width and height? I've noticed that using the width ...

Send the object containing a Dictionary<string, int> parameter to the WebMethod

I encountered an error that says: "Cannot convert object of type 'System.String' to type 'System.Collections.Generic.Dictionary2[System.String,System.Int32]'","StackTrace":" at System.Web.Script.Serialization.ObjectConverter.ConvertObje ...

What is the process for submitting and storing a collection of files in a database as a list?

I am trying to implement a feature in my MVC project where users can upload multiple files and see them listed before submitting the form. However, I am facing some challenges with finding a solution for this. Demo: My goal is to allow users to add multi ...

Verifying the value associated with the "type" attribute of an input field

I need to create test cases for automation testing. My goal is to verify if the password fields in my form contain type="password" attribute for input elements... Is there a way to achieve this using jquery? Thank you. ...

What is the best way to utilize RxJs with jQuery's ajax function?

Here is how I've set it up: Rx.Observable.fromPromise($.ajax({ url: url + postal_value + '&types=(regions)&location=51.509865,-0.118092&key=' + key, type: "GET", datatype: "json" })); However, the aj ...

Dealing with TSLint errors within the node_modules directory in Angular 2

After installing the angular2-material-datepicker via NPM, it is now in my project's node_modules folder. However, I am encountering tslint errors that should not be happening. ERROR in ./~/angular2-material-datepicker/index.ts [1, 15]: ' should ...

Retrieving a particular value from an array received through Ajax in JavaScript

Ajax functionality $("#panchayat").change(function(){ var param = {'panchayat_id':$(this).val()}; alert (param['panchayat_id']); $.ajax({ type : 'POST', url : '<?php echo base_url();?>index.php/parent_taluk' ...

When attempting to call a Firebase Cloud Function URL in an AngularJS $http request, an Access Control Origin Error

I recently created a cloud function that involves linking with Plaid. I'm currently working on calling this function using AngularJS's $http method. While the cloud function code is being executed, I encountered an error in my console instead of ...

Unusual jQuery error notification

Short Receiving Error in syntax, unrecognized expression: [object Object] @ jquery.js:4267 This code snippet is from jQ: Sizzle.error = function( msg ) { throw new Error( "Error in syntax, unrecognized expression: " + msg ); // Line 4267 }; Detaile ...

Using MongoDB map-reduce with Node.js: Incorporating intricate modules (along with their dependencies) into scopeObj

I am currently immersed in developing a complex map-reduce process for a mongodb database. To make the code more manageable, I have organized some intricate sections into modules that are then integrated into my map/reduce/finalize functions through my sco ...

What is the most effective method for utilizing AJAX to load external resources?

Looking to load external resources from another server such as css, templates, and data, but unsure of the best approach? Often when attempting to load external files, the Access-Control-Allow-Origin problem arises. Here are a few possible solutions: - U ...

Guide on building a REST API with Node.js Express.js and OracleDB to perform database updates

Looking for assistance with creating an API in Node.js to fetch and update data on the frontend. I am able to retrieve data using the provided code, but facing challenges updating it. React.js is being used for the frontend. var express = require("expr ...

Seeking to develop a pair of functions for submitting data via my website's form

I need to pass form data to both Docusign and Zapier with just one button click using JavaScript. When the Submit button is pressed, I want the data to be sent to Zapier without opening a success page and then redirect to the Docusign page with all the in ...

Adjust the width of a div element to a specific size, center the div horizontally, and justify

My issue may be small, but I am struggling to find a solution. I have a content header that is 864px wide with a background image repeated vertically and a footer image. I now have a <div> positioned over the background image and I want it to be 855p ...

The Challenge of Logging in with the Loopback Angular SDK

I have set up a "user" named model with the base class of "User". I'm attempting to log in a user on my Angular App using the service generated by lb-ng, but it doesn't seem to be working. When I call User.login() in my Login controller, providin ...

After upgrading to version 4.0.0 of typescript-eslint/parser, why is eslint having trouble recognizing JSX or certain react @types as undefined?"

In a large project built with ReactJs, the eslint rules are based on this specific eslint configuration: const DONT_WARN_CI = process.env.NODE_ENV === 'production' ? 0 : 1 module.exports = { ... After upgrading the library "@typescript-es ...

What is the best way to create a new object in a Vue component with optimal efficiency?

Currently, I am working on initializing a map that would be utilized in my calculatePrice function. calculatePrice(key) { let prices = new Map({ 0: 17, 1: 19, 2: 24, 3: 27, 4: 30, 5: 46, 6: 50 ...

Concatenate a variable string with the JSON object key

I am currently working on a request with a JSON Object structure similar to the following: let formData = { name: classifierName, fire_positive_examples: { value: decodedPositiveExample, options: { filename: 'posit ...