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

JavaScript preloader function isn't functioning properly when paired with a button

I'm currently working on developing a preliminary landing page for my game using JavaScript. I have integrated a class that overlays my main content, and added an 'onclick' function named fadeOut() for my button in JavaScript. However, the f ...

Troublesome Issue with ngAnimate and ngHide: Missing 'ng-hide-animate' Hook Class

I am working on a case where I need to add animation to a DOM object using the ngHide directive: Check out this example here Within this scenario, I have an array of JSON objects: $scope.items = [ {"key": 1, "values": []}, {"key": 2, "values": [ ...

Validating dropdown lists with Jquery

Custom Dropdownlist: <div class="col-md-2"> <div class="form-group"> <label for="field-3" class="control-label">Priority</label> <select id="lstpriority" class="custom-selectpicker" data-live-search="true" da ...

Fetching database entries upon page load instead of using the keyup function in JavaScript

Here is an HTML form input provided: <input type="text" id="username" value=""> In this scenario, when a username like "John" is entered and the enter button is pressed, the script below retrieves database records: $(function(){ //var socket = ...

Experiencing difficulties with incorporating cURL data into MySQL using Simple Dom Parser

Hey there! I'm currently trying to figure out the best way to save my scraped data to a MySQL database. It seems like nothing is getting inserted into the database, and I suspect it might be due to the format of the data I'm passing. Should I con ...

Image swaps with timer for button

I am working on a project where I have a page with 5 image buttons arranged horizontally. The objective is to have the images on each button change sequentially every 3 seconds in a continuous loop. Here is my code: $(document).ready(function (){ Beg ...

What is the mechanism behind the functioning of StackOverflow's notification system?

Could you explain the technique that is utilized to transmit and receive data from the client to the server? How does it manage to provide almost real-time results when new changes take place? Can anyone demonstrate the code being used for this process? ...

jQuery - patience is required until all elements have completely faded away

I am facing a unique challenge: I need to trigger an action after two specific elements have been faded out simultaneously. The code snippet for this task is as follows: $("#publish-left, #publish-right, #print-run").fadeOut(function(){ //do something ...

As I scroll, I hope the texts will stay fixed against the backdrop image

Is it possible to make the #home section fixed to the background while scrolling, including all the texts and buttons? I envision it like having texts embedded in an image. The text is located in the middle left of the page (let's keep this as default ...

Having trouble integrating RGraph into my HTML page with AJAX

As I work on developing a simple webpage layout with both a static header and footer, I'm encountering some challenges in updating content dynamically. The left side menu triggers an ajax request when clicked, which should update the text on the right ...

Completely place one element with respect to its sibling element

I am currently facing a situation where I have implemented a Navigation bar wrapper that reveals an overlay across the entire page when clicked. In order for this setup to function correctly, all the elements that the overlay covers must be sibling elemen ...

"Exploring the world of custom middleware in NextJs on a localhost

Question regarding nextjs page middleware: the documentation states that the request object should include geo, IP, ua, cookies, and nexturl properties. Visit the link for more information. I am attempting to retrieve the user's location using page m ...

Having trouble retrieving a base64 encoded image from a MySQL database using PHP

Within my MySQL database, there is a longblob field that stores a binary value representing an image uploaded through my website. I am currently attempting to retrieve the image using: <?php while($record = mysqli_fetch_assoc($result)): ?> <div&g ...

Obtain the values from this JSON array

o = { "photos": { "page": 1, "pages": 46, "perpage": 5, "total": "230", "photo": [{ "id": "6643924777", "owner": "34653895@N08", "secret": "3b7c2f6469", "server": " ...

Encountering a value accessor error when attempting to test a simple form in Angular 4 and Ionic 3

My ionic form is quite simple: <ion-header> <ion-navbar> <ion-title>Foo</ion-title> </ion-navbar> </ion-header> <ion-content padding> <form [formGroup]="fooForm"> <ion-item> ...

Clicking on a jQuery element will reveal a list of corresponding elements

I've retrieved a list of elements from the database and displayed them in a table with a button: <a href="#" class="hiden"></a> To show and hide advanced information contained within: <div class="object></div> Here is my jQ ...

Managing global HTTP response errors on Vue/axios using Vuex

I've encountered an issue in my VueJS SPA where a strange limbo state occurs. The application fails to recognize that the JWT token has expired, leading it to still display as if the user is logged in. This typically happens after periods of hibernati ...

What is the best way to increase the spacing between buttons in a Bootstrap navigation bar?

Can anyone guide me on how to add space between each button in this Navigation Bar? I want them to be separated, similar to this example. I am using bootstrap 5. <nav class="navbar navbar-expand-lg navbar-light bg-light shadow-sm bg-body"&g ...

Do XAML-based apps on Windows 8 provide a noticeable speed advantage over those built with HTML and CSS?

We are in the process of developing a photo-heavy Windows 8 Metro-style app and are concerned about UI performance. While choosing Objective-C over HTML for iOS was an easy decision to achieve the necessary UI performance, we are unsure about the speed com ...

The assigned type does not match the type 'IntrinsicAttributes & { children?: ReactNode; }'. This property is not assignable

I have been struggling to resolve this issue, but unfortunately, I have not found a successful solution yet. The error message I am encountering is: Type '{ mailData: mailSendProps; }' is causing an issue as it is not compatible with type &apos ...