Discover the process for simulating a browser zoom using JavaScript

Is there a way to control the browser's zoom level using JavaScript? I decided to create my own solution to override the default browser zoom behavior.

The current code works fine if starting from a scale of 1, but I'm facing an issue when already zoomed in and trying to zoom further by moving the cursor to another part of the image. The zoom focus seems to jump further than expected because changing the transform-origin causes the entire image to shift. Perhaps setting the transform-origin is not the most suitable approach...

var myDiv = document.querySelector(".container");
var img = myDiv.querySelector("img");

var scale = 1.0;

myDiv.addEventListener('wheel', function (ev) {
  if(!ev.ctrlKey)
  {
    return;
  }
  ev.preventDefault();
  const rect = myDiv.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;
  img.style.transformOrigin = x + "px " + y + "px"
  
  scale += event.deltaY * -0.005;

  // Apply scale transform
  img.style.transform = `scale(${scale})`;
})
.container {
  width: 600px;
  height: 200px;
  margin: auto;
  border: 1px solid gray;
  overflow: hidden;
}

img {
  width: 100%;
  transform: scale(1.0);
}
<div class="container">
  <img src="https://picsum.photos/id/200/600/200">
</div>

Answer №1

Make the most of the transform: scale(1.5) property

var myDiv = document.querySelector(".container");
var img = myDiv.querySelector("img");

var scale = 1.0

myDiv.addEventListener('mousemove', function(ev) {
  const rect = myDiv.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;
  img.style.transformOrigin = x + "px " + y + "px"

})

myDiv.addEventListener('wheel', function (ev) {
  ev.preventDefault();

  scale += event.deltaY * -0.001;

  // Implementing scale transformation
  img.style.transform = `scale(${scale})`;
})
.container {
  width: 600px;
  height: 200px;
  margin: auto;
  border: 1px solid gray;
  overflow: hidden;
}

img {
  width: 100%;
  transform: scale(1.0);
}
<div class="container">
  <img src="https://picsum.photos/id/200/600/200">
</div>

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

Prevent the page from scrolling while the lightbox is open

I am struggling with a lightbox that contains a form. Everything is functioning properly, but I need to find a way to prevent the HTML page from scrolling when the lightbox is active. <a href = "javascript:void(0)" onclick=" document.getElementById(& ...

What is the best way to apply an animation class to a modal upon clicking a button?

When I click the "x" button on the modal, I want the animation to occur. However, what currently happens is that the modal closes without the animation. Then, upon reopening the modal, the animation occurs without any clicking involved. Below is my curren ...

What methods can be used to avoid regular expressions when searching for documents in MongoDB?

I am using a simple regular expression-based search in MongoDB like this: router.get('/search', function (req, res, next) { var text = req.query.text; collection.find({text: new ReqExp(text, 'ig')}, function (err, result) { ...

Redux: utilizing yield within an unrecognized function

Hey there! I am brand new to Reudx-Saga and have been experimenting with it for the past few days. I feel pretty comfortable with generators, actions, redux-stores, sagas, and other concepts. Overall, I have a good amount of experience with JavaScript. C ...

What is the best way to structure a nested object model in Angular?

Issue occurred when trying to assign the this.model.teamMembersDto.roleDto to teamMembersDto. The error message states that the property roleDto does not exist on type TeamMembersDropdownDto[], even though it is nested under teamMembersDto. If you look at ...

There appears to be an issue with the server, as it is reporting a TypeError with the _nextProps.children property not

As a newcomer to coding, this is my first question on the forum. I appreciate your understanding and patience as I navigate through some challenges. I'm currently working on making my NextJS SSR app responsive, but after modifying the index.js and ot ...

Matching queries precisely in MongoDB

I developed an Express.js API with MongoDB integration that filters products based on a filter property. The issue I am facing is ensuring that the API output exactly matches the filter property criteria. Currently, if Product A has [{name: 'a', ...

Controlling the Quantity of Selected Checkboxes with JavaScript

I am facing an issue with implementing multiple checkboxes with limits in JavaScript, as shown below. $(".checkbox-limit").on('change', function(evt) { var limit = parseInt($(this).parent().data("limit")); if($(this).siblings(':checked&ap ...

Update the page with AJAX-loaded content

I am currently utilizing a .load() script to update the content on a webpage in order to navigate through the site. This is resulting in URLs such as: www.123.com/front/#index www.123.com/front/#about www.123.com/front/#contact However, I am encountering ...

Tips for concealing a dynamic table element in Angular 9

I have dynamically generated columns and rows in a table. Here is my HTML for the table component: <table id="tabella" class="table table-striped table-hover"> <thead class="thead-dark"> <tr> <th *ngFor="let header of _ob ...

Unable to create a polygon on the Google Maps API using GPS coordinates inputted from a text field

I am currently developing an interactive map using the Google Maps API. The map includes a floating panel with two input fields where I can enter GPS coordinates. My goal is to create markers and connect them to form a polygon. While I can easily draw lin ...

Is it possible to reset the existing localStorage value if we access the same URL on a separate window?

In my app, there are two different user roles: admin and super admin. I am looking to create a new window with a Signup link specifically for registering admins from the super admin dashboard. Is it possible to achieve this functionality in that way? Cu ...

Display three images with titles in a row using CSS

I'm trying to align 3 figures with captions horizontally in the middle of the page, side by side, but so far I've only been able to do it vertically. How can I achieve this using just HTML5 and CSS? This is my current HTML: <div class="r ...

Are you ensuring compliance with licensing in your Webpack bundles?

Can webpack be used to verify license compliance? I'm looking for a way to ensure that the license headers from all modules built by webpack are included in the final output file. How can we confirm this is happening? Furthermore, I am also intereste ...

The Bootstrap tab feature is malfunctioning when a tab is using data-target instead of href

While developing bootstrap tabs for an Angular app, I decided to use the data-target attribute instead of the href attribute to avoid any interference with routes. Here's a snippet of how I structured the tabs: <ul class="nav nav-tabs" id="myTab"& ...

"Utilizing FileReader to seamlessly integrate data into FormData without the risk

Currently, I'm in the process of constructing an ajax file uploader. This is made possible thanks to the recently introduced FormData interface. Everything seems to work as expected when using the original file. However, I encounter issues when conver ...

Error encountered on Facebook Like button: The large button is failing to show the total number of likes received

Despite functioning flawlessly for months, the large Facebook Like button has suddenly stopped showing the number of "Likes". Strangely, the compact version is still working fine, but the larger button is concealing the count. I am using a Mac and have obs ...

Converting string to JSON format by splitting it based on names

I recently manipulated a string containing the values "title:artist" by utilizing the str.split method : res = song.split(":"); The resulting output is as follows: ["Ruby","Kaiser Chiefs"] Now, I am curious about how to include the name in this array f ...

What are the steps to implementing partial page functionality with the $http service in Angular?

Could someone assist me with executing an operation once a partial page has been successfully loaded using the $http service in Angular? The operation involves checking a checkbox based on the scope value. I have included the source code below: Here i ...

Refresh cloned element after making changes to the original element

Just starting to explore Jquery and looking for some guidance to get me started :) Question: I'm facing an issue with a cart total price that is displayed in a different part of the page using clone(). I want this cloned price to automatically update ...