Reducing Image Size in JavaScript Made Easy

I need help with a project where I want the image to shrink every time it's clicked until it disappears completely. I'm struggling to achieve this, can someone assist me?

Here is the HTML code I have:

    <html lang="en" dir="ltr">
  <head>
    <link rel="stylesheet" href="main.css">
    <meta charset="utf-8">
    <title>Stupid Project</title>
  </head>
  <body>
    <header class="header-top">
      <h1>Shrink the image</h1>
      <a href="#"></a>
    </header>
    <img src="D:\MATEUS\Programação\Stupid project\images\levi.png" alt="Levi" id="image">
  </body>
</html>
<script type="main/javascript" src="jquery-3.3.1.js"></script>

And here is the CSS code I am using:

@import "variables.css";
@import url('https://fonts.googleapis.com/css2?family=Ubuntu:wght@300&display=swap');

*
{
  margin: 0%;
  font-family: 'Ubuntu', sans-serif;
  background-color: var(--body-color);
}

.header-top
{
  background-color: var(--body-color);
  height: 49px;

}

.header-top > h1
{
  color: white;
  display: inline-block;
  vertical-align: top;
  margin-left: 10px 10px;
}

#image
{
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
  margin-top: 90px;
  border-radius: 20px;
}

Answer №1

To resize the image on each click, you can follow these steps:

  • Start by setting the initial scale of the image to 1 using a CSS variable (--scale).
  • Add an event listener to the image.
  • When the image is clicked, check the current value of --scale, decrease it by 0.1, if it's not already 0.

    <html lang="en" dir="ltr>
  <head>
    <link rel="stylesheet" href="main.css">
    <meta charset="utf-8">
    <title>Image Resizing Project</title><style>
*
{
  margin: 0%;
  font-family: 'Ubuntu', sans-serif;
  background-color: var(--body-color);
}

.header-top
{
  background-color: var(--body-color);
  height: 49px;

}

.header-top > h1
{
  color: white;
  display: inline-block;
  vertical-align: top;
  margin-left: 10px 10px;
}

#image
{
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
  margin-top: 90px;
  border-radius: 20px;
  transform: scale(var(--scale));
}
</style>
  </head>
  <body>
    <header class="header-top">
      <h1>Resize Image</h1>
      <a href="#"></a>
    </header>
    <img src="https://picsum.photos/id/1016/1024/768" alt="example picture" id="image">
    <script>
    const image = document.getElementById("image");
    image.style.setProperty('--scale', 1);
    image.addEventListener("click", function () {
       const curScale = image.style.getPropertyValue('--scale');
       if (curScale > 0) {image.style.setProperty('--scale', curScale - 0.1); }  
    });
    </script>
  </body>
</html>

Answer №2

I managed to solve the issue, and here is an example of the code that fixed it:

HTML:

<button type="button" id="button" onclick="zoomout()">Click Me!</button>
    <img src="https://images.pexels.com/photos/1108099/pexels-photo-1108099.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" id="image">

CSS:

#image
{
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
  margin-top: 0px;   /* 90px */
  margin-bottom: 10px;
  border-radius: 20px;
  transition: all 1s;
}

#button
{
  color: white;
  margin-left: 570px;
  margin-top: 39px;
  margin-bottom: 0%;
  padding: 15px 32px;
  background-color: var(--button-color);
}

JavaScript:

function zoomout() {
  var pic = document.getElementById("image");
  var currentWidth = pic.clientWidth;
  pic.style.width = (currentWidth - 100) + "px"
}

Answer №3

To gradually decrease the image width by one unit at a time, you can implement a transition effect on the image to visualize the changes.

const img = document.querySelector("img");
const imgWidth = getComputedStyle(img, null).getPropertyValue('width')

document.querySelector("button").addEventListener("click", () => { 
  for (let i = parseInt(imgWidth); i >= 0; i--) {
    img.style.width = `${i}px` 
  }
})
img {
  display: block;
  width: 200px;
  transition: all 1s;
}

button {
  margin-bottom: 5px;
}
<button>Click</button>
<img src="https://images.unsplash.com/photo-1618141411216-96de9f2bd309?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyN3x8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" />

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

Exploring the applications of the `this` keyword within a jQuery-based JavaScript object

Recently, there has been a challenge in creating a JavaScript object with the specific structure outlined below: function colorDiv(div){ this.div=div; this.div.bind("click",this.changeColor) this.changeColor(){ this.div.css(" ...

Stingray Riverbed SteelApp, showcasing an image on a maintenance landing page

We have implemented a feature on riverbed stingray that displays a maintenance page whenever the system administrator needs to update the application. In order to achieve this, we designed a custom HTML page with a logo image and uploaded both the .html an ...

Caution: The file path in node_modules/ngx-translate-multi-http-loader/dist/multi-http-loader.js relies on the 'deepmerge' dependency

My micro-frontend angular project is using mfe (module federation). I recently updated it from angular 13 to 14 and encountered some warnings such as: node_modules\ngx-translate-multi-http-loader\dist\multi-http-loader.js depends on ' ...

Can you provide instructions on how to configure the npm settings to use the current directory in a pre

I'm currently working on setting the installation directory from where the user is installing to an npm config variable. This will help me reference it in my installation script. Can anyone advise if there is a command line solution for this or will ...

Updating Hidden Field Value to JSON Format Using jQuery and JavaScript

var jsonData = [{"Id":40,"Action":null,"Card":"0484"}]; $('#hidJson', window.parent.document).val(jsonData); alert($('#hidJson', window.parent.document).val()); // displays [object Object] alert($('#hidJson', window.parent.doc ...

Issues with AngularJS compatibility on Internet Explorer 8

Recently, I've been developing a new Angular app and I'm trying to ensure that it's compatible with IE8. It seems like the app is loading in the routing information and the template partially, but I keep encountering an error in the console ...

display a new feature immediately upon the user's login

I encountered a scenario where the user is supposed to log in, and upon successful login, another component should be displayed. However, this functionality is not working as expected for me. I have to click the login button again or refresh the page to vi ...

Guide to sending a similar request as a curl command through a JavaScript file

After reviewing this Stack Overflow post titled "JavaScript post request like a form submit", I came across a similar situation. Currently, I have a curl command that performs as expected: curl -v -X POST -H "application/json" -H "Content-type: applicatio ...

What is the best way to add a character within a YouTube JSON link?

Fetching json data from a link, the youtube format in the link is http:\/\/www.youtube.com\/watch?v=UVKsd8z6scw. However, I need to add the letter "v" in between this link to display it in an iframe. So, the modified link should appear as ht ...

Using force-directed layout to access and retrieve specific data from external or internal data sources

Just starting out with d3js and currently working on modifying the Force directed layout found at http://bl.ocks.org/mbostock/1153292 I have managed to make it so that when I hover over the node circles, the corresponding source value filenames should app ...

Using Vue.Js to link a value to a checkbox within a component

I'm currently developing a custom component that wraps around a checkbox (similar to what I've done with text and number input types), but I'm facing an issue with binding the passed-in value correctly. Here's the structure of my compo ...

Is it possible to incorporate a variable into an object?

If you are wondering whether it is possible to utilize a variable in the following scenario, the reason for my inquiry is connected to the potential of utilizing an input element to dynamically modify the variable: var str = "pineapples" var cost = { pine ...

Tips on ensuring data cleanliness in jQuery input fields

Before sending the ajax request, I want to sanitize the form fields for added security. Currently, my Javascript code looks like this: jQuery(document).ready(function($) { $('#login-form').submit(function(e) { e.preventDefault(); // pr ...

Displaying all API data by default in Vue.js, even with filters, sorting, and search enabled - how can it be done?

I am currently utilizing Vue.js version 3 and below is the code snippet: <template> <h5>List of Products</h5> <h3>Filter</h3> <button v-on:click="resetOptions">Reset</button> & ...

The absence of essential DOM types in a TypeScript project is causing issues

Recently, I've been working on setting up a web app in TypeScript but I seem to be missing some essential types that are required. Every time I compile using npm run build, it keeps throwing errors like: Error TS2304: Cannot find name 'HTMLEleme ...

I have encountered an issue where after declaring a JavaScript variable on a specific page, including the JavaScript file does not grant access to it

<script type="text/javascript"> $(document).ready(function () { var SOME_ID= 234; }); </script> <script type="text/javascript" src="<%= HtmlExtension.ScriptFile("~/somefile.js") %>"></script> ...

Invoke the function for every element during the mapping process

I am attempting to call a function in React Native maps for each element. This function will randomly determine properties of the rendered component, making sure that each component is unique. The renderComponent function takes an argument called item as w ...

Preventing unauthorized access to files in ExpressJS public directories

Is there a way to conceal files served by the Node server? Despite my attempts to redirect certain files and directories, Express 4.X does not seem to cooperate. I have also experimented with sending 4XX HTTP responses when specific files are requested, bu ...

AngularJS allows for the passing of a function value into another function

Is there a way for me to pass a value from one function to another? Here is an example of what I am trying to achieve: HTML <div> <li ng-repeat="language in languages" ng-click="myFirstFunction(firstValue) {{lang ...

Having Difficulty Converting JavaScript Objects/JSON into PHP Arrays

This particular inquiry has no relation to the previously mentioned identical answer/question... In JavaScript, I am dealing with a substantial list of over 1,000 items displayed in this format... var plugins = [ { name: "Roundabout - Interac ...