Extracting the magnifying glass from the picture

After implementing a function to add a magnifying glass (.img-magnifier-glass) on button click, I am now looking to remove the glass by clicking the "cancel" button. However, I am unsure of how to write this function to interact with the "magnify" function.

I attempted to create a function that adds a class which sets the display property to none on ".img-magnifier-glass".

function magnify(imgID, zoom)
{
    var img, glass, w, h, bw;
    img = document.getElementById(imgID);
    /*create magnifier glass:*/
    glass = document.createElement("DIV");
    glass.setAttribute("class", "img-magnifier-glass");
    /*insert magnifier glass:*/
    img.parentElement.insertBefore(glass, img);
    /*set background properties for the magnifier glass:*/
    glass.style.backgroundImage = "url('" + img.src + "')";
    glass.style.backgroundRepeat = "no-repeat";
    glass.style.backgroundSize = (img.width * zoom) + "px " + (img.height * zoom) + "px";
    bw = 3;
    w = glass.offsetWidth / 2;
    h = glass.offsetHeight / 2;

    /*execute a function when someone moves the magnifier glass over the image:*/
    glass.addEventListener("mousemove", moveMagnifier);
    img.addEventListener("mousemove", moveMagnifier);
    /*and also for touch screens:*/
    glass.addEventListener("touchmove", moveMagnifier);
    img.addEventListener("touchmove", moveMagnifier);
    function moveMagnifier(e)
    {
        var pos, x, y;
        /*prevent any other actions that may occur when moving over the image:*/
        e.preventDefault();
        /*get the cursor's x and y positions:*/
        pos = getCursorPos(e);
        x = pos.x;
        y = pos.y;
        /*prevent the magnifier glass from being positioned outside the image:*/
        if (x > img.width - (w / zoom)) { x = img.width - (w / zoom); }
        if (x < w / zoom) { x = w / zoom; }
        if (y > img.height - (h / zoom)) { y = img.height - (h / zoom); }
        if (y < h / zoom) { y = h / zoom; }
        /*set the position of the magnifier glass:*/
        glass.style.left = (x - w) + "px";
        glass.style.top = (y - h) + "px";
        /*display what the magnifier glass "sees":*/
        glass.style.backgroundPosition = "-" + ((x * zoom) - w + bw) + "px -" + ((y * zoom) - h + bw) + "px";
    }
    function getCursorPos(e)
    {
        var a, x = 0, y = 0;
        e = e || window.event;
        /*get the x and y positions of the image:*/
        a = img.getBoundingClientRect();
        /*calculate the cursor's x and y coordinates, relative to the image:*/
        x = e.pageX - a.left;
        y = e.pageY - a.top;
        /*consider any page scrolling:*/
        x = x - window.pageXOffset;
        y = y - window.pageYOffset;
        return { x: x, y: y};
    }
}


function onClick()
{
    magnify("img1", 1.5);
    magnify("img2", 1.5);
    magnify("img4", 1.5);
}
<div>
  <div class="slideshow-container">
      <button onclick = "onClick()" id="btn1" type="button" class="btn"> Zoom In</button>
        <button onclick = "zoomOut()" id= "btn2" type= "button" class="btn" >Cancel</button>
      <div class="img-magnifier-container mySlides">
        <img id = "img1" src="img1.jpg" width="800" height="600">
      </div>
      <div class="img-magnifier-container mySlides">
        <img id = "img2" src="img2.jpg" width="800" height="600" >
      </div>
      <div class="img-magnifier-container mySlides">
        <img id = "img4" src="img4.jpg" width="800" height="600">
      </div>
  </div>

Answer №1

To remove the additional elements, you must identify and eliminate them. As the zoom script assigns all of these elements the img-magnifier-glass class name, you can follow this procedure:

function clearZoom() {
   var glassElements = document.querySelectorAll(".img-magnifier-glass");
   for(var i=0;i<glassElements.length;i++) {
      glassElements[i].parentNode.removeChild(glassElements[i]);
   }
}

Answer №2

I already completed that task! Thank you for the zoomOut feature.

Here is my external JavaScript code:

function magnify(imgID, zoom) {
    var img, glass, w, h, bw;
    img = document.getElementById(imgID);
    
    /* Create a magnifier glass: */
    glass = document.createElement("DIV");
    glass.setAttribute("class", "img-magnifier-glass");
    
    /* Insert the magnifier glass: */
    //img.parentElement.hidden(glass, img);
    img.parentElement.insertBefore(glass, img);
    
    /* Set background properties for the magnifier glass: */
    glass.style.backgroundImage = "url('" + img.src + "')";
    glass.style.backgroundRepeat = "no-repeat";
    glass.style.backgroundSize = (img.width * zoom) + "px " + (img.height * zoom) + "px";
    bw = 3;
    w = glass.offsetWidth / 2;
    h = glass.offsetHeight / 2;
    
    /* Trigger a function when moving the magnifier glass over the image: */
    glass.addEventListener("mousemove", moveMagnifier);
    img.addEventListener("mousemove", moveMagnifier);
    
    /* Also for touch screens: */
    glass.addEventListener("touchmove", moveMagnifier);
    img.addEventListener("touchmove", moveMagnifier);
    
    // More functions here...
}

I followed the instructions from W3Schools [https://www.w3schools.com/howto/howto_js_image_magnifier_glass.asp][1]

In my HTML file, I implemented a switch to showcase various images:

function showmobile(mob) {
    document.getElementById("mymob").className = "img_show";

    switch (mob) {
        case "mob1":
            document.getElementById("mymob").src = "iphone12.jpg";
            zoomOut();
            magnify("mymob", 3);
            break;

        case "mob2":
            document.getElementById("mymob").src = "samsung.jpg";
            zoomOut();
            magnify("mymob", 3);
            break;

        // More cases here...

    }
}
And also in HTML

<tr>
    <td>iphone 12   </td>
    <td>128 GB  </td>
    <td>TrueDepth   </td>
    <td>LiDAR</td>
    <td>IOS 14  </td>
    <td>1.229,00 €    </td>
    <td><button class="iconbtn" onclick="showmobile('mob1')"><i class="fa fa-eye" ></i></button></td>
</tr>

// Additional table rows here...

Thank you once again. I made an effort to share my solution with others.

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

Any suggestions for a quicker method to manage state changes between OnMouseDown and OnMouseUp events in React?

I am attempting to create a window that can only be dragged from the top bar, similar to a GUI window. Currently, I have set up state updates based on OnMouseDown and OnMouseUp events on the top bar. However, I am experiencing slow updates as it seems to ...

Using Jquery to find the class that matches the current element

Is it possible to select a specific div by its class when there are multiple divs sharing the same class and triggering the same function on button click? I only want to target the class where $(this) is located. I've experimented with .parent, .chil ...

Ways to expand HTML input fields to fill the whole table cell

Currently working on a calculator project and I'm facing an issue with making a HTML button span the entire cell. I've managed to stretch the button horizontally but struggling to get it to fill the cell completely. Curious as to why setting widt ...

Check a field for validation only when it is visible on the screen

One challenge I'm facing is with an asp.net webform. I have a hidden field that is only displayed when a user selects a radio button. The catch is, this hidden field needs to be mandatory only when it's visible; otherwise, I don't want it to ...

I keep encountering an error in the where clause when trying to update MySQL. What could be

I encountered an issue stating Unknown column 'CR0001' in 'where clause' while executing my code. Strangely, the error seems to be related to the id_scooter column rather than CR0001. Below is the snippet of my code: var update = "UPDA ...

Using React.js to establish a connection with a database

Can someone help me with connecting my reactjs to mysql? I have already installed mysql and followed the usual instructions, but I keep getting an error "TypeError: mysql.createConnection is not a function". Below are the codes I am working with. import ...

Is there a disparity in how the mandatory field validator functions in Edge compared to Chrome?

There doesn't seem to be any red color How can I ensure consistency? Both elements should either have color or none at all. <form action=""> <input id="email" type="email" required="required" /> <input type="submit" id="btnS ...

Position an HTML canvas at the very top of the webpage

Can someone help me figure out how to align a canvas element to the very top (0, 0) of a webpage? I attempted using margin: 0; padding: 0px;, but it didn't work. There always seems to be some white space at the top that I can't eliminate. ...

What are some creative ways to visually distinguish a TextField that is in readOnly mode?

I'm currently working on creating a form using the Material-UI library. I'm having difficulty figuring out how to distinguish my TextField when they are in readOnly mode versus edit mode. At the moment, they appear identical and I would like the ...

Is there a way in JavaScript to activate a web element by clicking on its center?

I have a webpage and I'm looking to simulate clicks using the console. I attempted to do so with the code snippet document.getElementById("myButtonId").click(), but it seems that the element only responds to clicks at its center location. Is there ano ...

Move the text to the following line if a horizontal scroll bar is visible using JavaScript/JQuery and CSS styling

I have a section with multiple div elements...how can I ensure that when there is horizontal scrolling in the section, the hidden divs shift to the next line? HTML <section id="a"> <div class="num"> <div class="num"> <div class="num" ...

Using Rails to reference an image in CSS

My application on Heroku, built with Rails, features a striking image as the background on the landing page. Since Heroku's file system is read-only, I made the decision to store these images (selected randomly) on AWS S3. In my .css(.scss) code, the ...

What is the process for reinserting a list item into the nested elements?

Looking for help with manipulating a menu in HTML? I have a menu that I want to modify by removing and adding list items. While I've had success removing items, I'm struggling to properly use the add method. Here's an example of what my menu ...

The API is returning a successful response code of 200 when the HEAD and OPTIONS methods are utilized

My API is up and running smoothly with a GET method in express. This is the code for my API: app.get('/healthcheck', (_req, res) => { res.status(200).send({ state: 'Healthy', timestamp: new Date(), uptime: process.upti ...

Implementing Event Listeners in Vue 3.0: A Guide to Attaching to the Parent Element

How can I attach an addEventListener to the parent element in Vue 3.x? I discovered that you can access the parent by using this code: import { getCurrentInstance, onMounted } from 'vue' onMounted(() => { console.log(getCurrentInstance() ...

The function did not execute properly, resulting in the express route returning no value

Encountering some issues with Express routes that are behaving inconsistently despite having identical code execution. The goal is to have a client application make API calls like this: async search(){ const query = this.$refs.searchInput.value; ...

I utilized the explode function in PHP to transform a string into an array. Now, I require assistance with manipulating

Currently, I am facing a challenge where I have converted a string into an array in PHP using explode. I need to pass this array to a separate JavaScript page and then access the data values from within. Below is the structure of the array in JavaScript o ...

Exploring the use of dictionaries within Django templates

views.py: return render(request,'images.html',temp) Temp Data: {'cluster1': ['temp/vinoth/cluster1/demo-pic94.jpg', 'temp/vinoth/cluster1/id1.jpg'], 'cluster2': ['temp/vinoth/cluster2/demo-pic94.jp ...

Tips for looping through each cell in a column of a DataTable to verify its content

I have a table generated using the jquery DataTables API. One of the columns displays word frequencies for each word in the table. If a frequency is less than 40, I want to change that cell to display "unranked" instead of the actual number. How can I ite ...

Is there a way to add a price to an object in JavaScript?

Purchasedata.find(function(err, purchasedatas) { if (err) { return handleError(res, err); } var totalprice = 0; for (var i = 0; i < purchasedatas.length; i++) { findProduct(i, function(i, price) { }); } ...