Struggling to remove an image while using the onmouseover event with a button?

I am encountering an issue with hiding an image using the onmouseover event not applied directly to it, but rather to a button element. The desired functionality is for the image to appear when the mouse hovers over and disappear when it moves away. Here's my current code:

    <script>
  function toggleImage(id) {
    var x = document.getElementById(id);
    if (x.style.display === 'none') {
        x.style.display = 'block';
    } else {
        x.style.display = 'none';
    }
}
</script>

This JavaScript function allows for dynamic toggling of images on mouseover, and in the HTML section you can find:

  
<!-- Example image elements -->
<img id="imgSWTCH1" src="https://www.shareicon.net/data/128x128/2016/10/20/846459_blue_512x512.png" width="100" height="100"/>
<img id="imgSWTCH2" src="https://www.writeraccess.com/wp-content/uploads/2014/08/blog-html-5.png" width="100" height="100"/>
<!-- Add more image elements as needed -->

<!-- Using buttons to trigger image toggling -->
<button onmouseover="toggleImage('imgSWTCH1')" onmouseout="toggleImage('imgSWTCH1')">Toggle Image 1</button>
<button onmouseover="toggleImage('imgSWTCH2')" onmouseout="toggleImage('imgSWTCH2')">Toggle Image 2</button>
<!-- Add more buttons to correspond with additional images -->

The `onmouseout` event currently changes the background color to orange, but the goal is to hide the corresponding image instead. However, assigning multiple IDs to an element poses a challenge. A potential solution would be implementing this functionality using jQuery or Angular.

Here is the Plunker link, make sure to expand the HTML section to view the complete code.

Answer №1

Here is a straightforward demonstration using JQuery:

View the example here

$(document).ready(function() {
  $('li').hover(function(e) {
      var imageID = $(e.currentTarget).attr('data-img-id');
      var $image = $('img[data-img-id="' + imageID + '"]');
      $image.show();
    },
    function(e) {
      var imageID = $(e.currentTarget).attr('data-img-id');
      var $image = $('img[data-img-id="' + imageID + '"]');
      $image.hide();
    });
});

Answer №2

Consider trying a single function for mouseover and another for mouseout. Instead of using the display property, try using the visibility property of the img to avoid any jumping elements.

Check it out here:
https://plnkr.co/edit/YeOgtFeEmNhRCgdQ0Mlp?p=preview

UPDATE

Here's the idea:

  function sfuncOver(imgId) {
    var x = document.getElementById(imgId);
    if (x.style.visibility === 'hidden') {
        x.style.visibility = 'visible';
    } else {
        x.style.visibility = 'hidden';
    }
  }

  function sfuncOut(imgId) {
    var x = document.getElementById(imgId);
    x.style.visibility = 'visible';
  }

...in JavaScript and in HTML:

 <td id="tab1" onmouseover="sfuncOver('imgSWTCH1')" onmouseout="sfuncOut('imgSWTCH1')">C</td>

...and so forth. However, implementing this with jQuery would be much more efficient :) This coding style is reminiscent of the 90s :)

Answer №3

If you have 7 functions that are all doing the same thing, consider creating one function and binding the element you want to hide to it. Check out this example on JSFiddle to see how it can be implemented:

Take a look at the JavaScript code below:

function toggleVisibility(element){
    if(element.style.display === "none") {
        element.style.display = "inline-block";
    } else {
        element.style.display = "none";
    }
}

Array.prototype.slice.call(document.getElementsByClassName('tab')).forEach(function(element){
    element.onmouseover = toggleVisibility.bind(this, document.getElementById(element.getAttribute('data-hide')));
});

Additionally, I've replaced the onmouseover attributes on the html elements with a data-hide attribute. This attribute specifies which element should be hidden when the mouseover event occurs.

Answer №4

Here is a suggested approach:

HTML:

<table >
              <tb id="tab1">C</tb> //ensure that the id is unique for each <tb>
              <br />
                (...)
          </table>  

Javascript:
(*)Remember to enclose the JavaScript within document ready function.

$(function() {
  $('#imgSWTCH1').hide();  
  $('#tab1').mouseover(function (e) {
     //e.stopPropagation();
      $('#imgSWTCH1').show();      
  });
  $('#tab1').mouseout(function (e) {
    //e.stopPropagation();
      $('#imgSWTCH1').hide();      
});

});

Answer №5

function toggleImageVisibility(){
    if(document.getElementById("image").style.visibility == "visible"){
        document.getElementById("image").style.visibility = "hidden";}
    else{
        document.getElementById("image").style.visibility="visible";
    }
}

function hideImageOnEnter(){
    document.getElementById("image").style.visibility = "hidden";
}

function showImageOnLeave(){
    document.getElementById("image").style.visibility="visible";
}
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'/>
<script src='script.js'></script>
</head>
<body>
<img onmouseover="hideImageOnEnter();" onmouseout="showImageOnLeave();" id="image" src="https://publicdomainvectors.org/photos/Microscope-BW.png"/>
<button onclick="toggleImageVisibility();" >Click Me</button>
</body>
</html>

Try running the code snippet and see how it works. Good luck!

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

Upon utilizing JSON.parse in Express, an unexpected token < in JSON was encountered at position 0 while attempting a client side fetch POST

I'm trying to send a basic object through a fetch request to my express server, but I keep encountering an error when attempting to log it. Currently, if I log req.body (with the header 'Content-Type': 'application/x-www-form-urlencode ...

Utilizing Page Objects to select dropdown list items in JavaScript for Protractor testing

I'm struggling with a particular issue during my testing process. The task requires selecting an item from a list as part of a form to create a new user. However, the test does not select an item from the list even though Protractor does not report an ...

Looking for some specific instances of binding attributes within custom AngularJS elements?

I am in the process of developing a custom tag that resembles the following: <mytag type="Big" /> where "type" is an attribute that will be linked to the component and set the text in a label, like so: <label>{{type}}</label> ... (oth ...

Can the color scheme be customized for both light and dark themes in Ant Design version 5?

After creating a hook that successfully toggles between light and dark modes in Chrome's Rendering panel, I noticed that the values in the ConfigProvider remain unchanged when switching themes. Can anyone suggest a workaround to modify the design toke ...

Customize Material-UI Icons styles in React app

I'm working on a React.js app with Typescript and I need to remove the default visited Material Icons coloring from an anchor tag. Here's the stylesheet I tried: const useStyles = makeStyles((theme: Theme) => createStyles( myAnchor: ...

Test an express + sequelize server using chai-http ping command

Currently facing challenges while setting up tests using Express and Sequelize. The testing framework being used is Mocha + Chai. Initially, only a ping test is being attempted. The code snippet from server.js: const express = require('express&apos ...

Sleek transition-ready zoom functionality for THREE JS with clickable controls

Hey there, I've been attempting to animate a transition between scenes in THREE js for quite some time now. I have successfully cleared the scene and recreated the next one, but the transition between them is proving to be quite challenging. I have cr ...

JavaScript code may fail to load on initial page load

My JavaScript function utilizes ajax and is triggered when a button is clicked. Oddly, the function works perfectly if you visit the page for a second time, but fails to work on the first visit. I've attempted to include window.onload, document.onlo ...

Struggling to align divs in HTML using CSS

Struggling with aligning my divs in the center of the parent div and keeping them inline. I have a parent "page" containing 6 other divs - "bg_01", "bg_02", "bg_03", "bg_04", "bg_05", "bg_06". They sit inline when the window is small, but when it's re ...

What is the best way to calculate the total duration (hh:mm) of all TR elements using jQuery?

I currently have 3 input fields. The first input field contains the start time, the second input field contains the end time, and the third input field contains the duration between the start and end times in HH:mm format. My goal is to sum up all the dur ...

Determine the total width by adding together the widths of all child elements

Does anyone know how to calculate the total width of parent element (#projects) based on the combined widths of all child elements (.project)? I tried using jQuery but couldn't get it to work. Any help would be greatly appreciated! Thank you! var to ...

Instructions on transferring an image to a server. The image is located on the client side within an <img> tag

Looking for an effective way to upload an image when the type is “file”? The goal here is to send an image from an image tag to the server without converting it into base64 due to size constraints. <form id="form-url"> <image src ...

What is the best way to retrieve a file using XMLHTTPRequest and Ajax?

I am currently using window.location.href to download a file, but this method requires a second call to my servlet which takes about 1 minute to generate the file. How can I download the file using XMLHTTPRequest instead? The solution should only work wi ...

What is the process for right-aligning components in BootStrap 5.0?

Currently, I am enrolled in an online course where the instructor utilizes Bootstrap 4. However, I decided to challenge myself by using Bootstrap 5.1 instead. I have been struggling with configuring my navigation bar elements to look like the ordered list ...

Assign a variable the source of the web subsurface A-frame setting

I want to utilize the websurface A-frame component () to change the URL of the websurface when a button is clicked. I have defined a variable called source and I want the websurface URL to be updated to the value of this variable upon clicking the button. ...

Some elements in the DOM appear to not be rendering even though they are present in the HTML source code

As a newcomer to web development, I have stumbled upon a perplexing issue. In my usage of d3.js (specifically the script found here), I have been attempting to incorporate additional features. I modified my JavaScript code to include a simple <p> ele ...

updating a div with URL redirection instead of global redirect

I am facing an issue with redirecting my website flow to the login page when a user clicks any link on the page after the session has expired (either due to timeout or manual logout from another window). In an attempt to solve this, I inserted the followi ...

Tips for sending values via props to a different component and the common error message: "Consider using the defaultValue or value props instead of setting selected on the <option> element"

Currently, I am attempting to pass the selected value using the prop: handle state change, but encountering two errors. Error 1 : Instead of setting selected on <option>, use the defaultValue or value props. Error 2 : A property 'active' ...

Feeling grateful: Enable scroll functionality for a log widget

I am currently utilizing the Blessed library to create a dashboard within the terminal. My issue lies in making the log widget scrollable. Despite implementing the code below, I am unable to scroll using my mouse wheel or by dragging the scrollbar: var l ...

Identify support for the :first-child pseudo-class

Is there a way to determine with JavaScript whether the browser is compatible with the CSS :first-child selector? ...