When the mouse leaves, the background image will revert back to its original setting

https://i.stack.imgur.com/Ojd0Q.pngI need assistance in reverting a div's background image back to its default state using the onmouseleave method. Below is the HTML and JS code I have been working on:

  <script type="text/javascript">

function displayImage(event) {
event = event || window.event;
var targetElement = event.target || event.srcElement;

 if (targetElement.tagName == "IMG") {
    console.log(document.getElementById("viewer"));
    document.getElementById("viewer").style.backgroundImage = 'url(' + targetElement.getAttribute("src") + ')';
 }
}

function leaveImage(event) {
  event = event || window.event;
  var targetElement = event.target || event.srcElement;

  if (targetElement.tagName != "IMG") {
    document.getElementById("viewer").style.backgroundImage: URL();
  }
}

}

Both displayImage and leaveImage functions are called within the same HTML div tag like this:

<div class="thumbnails" onmouseover="displayImage(event)">

In summary, my goal is to reset the background image of the "viewer" div element to its default once the mouse leaves it, by using separate functions for each action. Is my approach correct? Thank you for your assistance!

Thank you all!

Answer №1

First things first; the reason you see [Object HTML Collection] is because you are using getElementsByTagName, which retrieves all elements with that tag name. To only get one element, consider giving it an ID and using getElementById instead. This way, you will only retrieve the single element.

Also, remember to store the original text of the p tag somewhere. Here's an example of saving it in a variable:

HTML:

<p id="tip">Hover over the image to display larger</p>

Javascript:

var originalText; // Define this outside functions
function displayImage(event) {
    event = event || window.event;  
    var targetElement = event.target || event.srcElement;

    originalText = document.getElementById("tip").innerHTML;
    var altText = targetElement.getAttribute("alt");
    document.getElementById("viewer").innerHTML = altText;


     if (targetElement.tagName == "IMG") {
        console.log(document.getElementById("viewer"));
        document.getElementById("viewer").style.backgroundImage = 'url(' + targetElement.getAttribute("src") + ')';
    }
}

function leaveImage(event){
    event = event || window.event;
    var targetElement = event.target || event.srcElement;

    document.getElementById("viewer").innerHTML = originalText; 

    if (targetElement.tagName != "IMG") {
        document.getElementById("viewer").style.backgroundImage = URL();
      }
 }

Answer №2

It seems like there might be a small error on this line, instead of ":" it should be "=":

document.getElementById("viewer").style.backgroundImage = URL();

This correction could potentially solve the problem...

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 html.dropdown feature is not maintaining the selected value chosen

After successfully filling out my form and submitting data to the database, I encountered a problem with the drop downs on the form not showing the selected value if the model fails validation. Although the HTML clearly shows that the value of the dropdow ...

Error encountered: $(...).pickadate is not defined as a function

I am currently working on a basic web project that involves a simple form where users enter their name, birthday, and university degree. I am utilizing Materialize and jQuery for this project. However, I have encountered a frustrating issue while trying to ...

Integrating a PHP function within an ECHO statement

Here is a code snippet I'm currently using in my Wordpress: function wpstudio_doctype() { $content = '<!DOCTYPE html>' . "\n"; $content .= '<html ' . language_attributes() . '>'; echo apply_filte ...

Struggling with developing a straightforward application with Angular-Material

My goal is to develop an application that utilizes the Angular Material navigation bar, as showcased in this example. Being relatively new to AngularJS, I'm facing an issue where my app loads but only displays a blank page. Below is the code snippet ...

Begin the ul element from the left-hand side

Check out my latest JSFiddle creation: http://jsfiddle.net/alonshmiel/Ht6Ym/2409/ I'm attempting to align the ul element on the left side of the page: I've experimented with the following CSS rules: margin-left:0px; float: left; Unfortunatel ...

In Internet Explorer 7, the combination of having a hasLayout property along with setting the position to relative,

Issue: Encountering a challenge in IE7 with a div containing a gradient and a flyout menu on hover. Although it may seem simple, applying position:relative to the container for accurate menu positioning conflicts with the filter/hasLayout combination. Ch ...

Exploring the capabilities of TabrisJs in conjunction with Upnp technology

Working with Upnp in TabrisJs seems to be a bit challenging. Even though it has good support for node packages, I am facing difficulties while dealing with Upnp. I included node-upnp-client in my package.json file. "dependencies": { "tabris": "^2.0 ...

Surfing the web with Internet Explorer means music downloads rather than streaming

My music website functions properly, however I am experiencing issues when accessing it through Internet Explorer. The internet download manager is downloading music from the site without any problems in Chrome and Firefox. Is there a way to prevent or b ...

Canceling a promise in a Vuex action

I am looking to implement the ability to cancel a running promise in my Vue component, specifically a promise returned by a Vuex action. In my scenario, the Vuex action is continuously polling an endpoint for status updates, and I need the capability to s ...

The Android Webview is experiencing difficulties with loading CSS styles and displaying the blockquote font color effect

I am facing an issue with loading HTML content in CSS through Android WebView. Despite having the code executed, I don't see any observable changes in font color for the text inside blockquote tags Here is the HTML code: <html> <head> ...

Exploring the bewilderment of retrieving values in a JavaScript

I'm confused about the return value of this code snippet: function foo() var ret = 0; var xhr=send_request( "bla", function() { // perform actions based on AJAX response // set the value of ret based on the response } ); return re ...

Using the Vuejs computed property for loop allows you to print all values, however, it ultimately only returns a

When using the Vuejs computed property 'for loop' to print all values, I am encountering an issue where it only returns one value. The code snippet provided below is intended to iterate through an array of 'bannerData' and extract IDs f ...

Tips for verifying the rendered view post data retrieval from an API in Vue JS

Having trouble retrieving data from the API using Vue JS and printing the page? After fetching the data, some elements may not render completely when trying to print, resulting in blank data being displayed. While using a setTimeout function may work for s ...

How do I go about showing every character on a separate line using a for loop?

var input = prompt("What is Lance attempting to convey?"); //user enters any text for (var i = 0; i <= input.length; i++) { var output = input.charAt(i); if (output == "e" || output == "o" || output == "a" || output == "u") { outp ...

Exploring the dynamic changes in user authentication state with Angular Fire subscriptions

At the moment, I have been listening to authentication state changes in my ngOnInit method of my AppComponent: export class AppComponent implements OnInit { constructor(public fireAuth: AngularFireAuth) { } ngOnInit(): void { this.fireAuth.auth ...

How to use Vanilla JavaScript to toggle a click event on a list item (LI) that

I have a script that scans through a webpage and identifies a unique string, for example: multus –a –um. The page contains several <LI> elements with various text content, including instances of multus –a –um. I need a solution to locate an & ...

Utilize Material UI's Datagrid or XGrid components to customize the rendering

There is a section from Material UI discussing renderHeader in the DataGrid and Xgrid components. https://material-ui.com/components/data-grid/columns/#render-header The documentation describes how to add additional content to the header, but what if I w ...

Leverage JavaScript to retrieve the formatting of an element from an external CSS stylesheet

Check out this HTML snippet: <html> <head> <link rel="stylesheet" type="text/css" media="all" href="style.css"> </head> <body> <div id="test">Testing</div> <script> ...

Keep track of the user's email address as they complete the form

I currently use a Google Form to gather information from employees who work in remote locations Emp No * Punch * Customer details / mode or travel All the data collected is stored in a Google spreadsheet structured as follows: Timestamp Emp No Punch ...

Guide on how to dynamically add AJAX JSON array response to an HTML table

Hey! I need some advice on how to dynamically append a JSON Array response to an HTML table after submitting a form using AJAX. Here's the scenario: This is my form : <form id="myForm" method="POST"> <input type=" ...