Change the background image when hovering over an element with vanilla JavaScript by utilizing data attributes

I would like to be able to change the background image of a <div> when hovering over a link. Initially, the <div> should not have a background image when the page loads for the first time.

This is my current setup:

<div class="background">
  <a href="#" data-bkgimg="link-1-bkg.jpg">Link 1</a>
  <a href="#" data-bkgimg="link-2-bkg.jpg">Link 2</a>
</div>

Here's what I want to achieve on hover:

<div class="background" style="background-image: url('link-1-bkg.jpg');">
  <a href="#" data-bkgimg="link-1-bkg.jpg" class="is-active">Link 1</a>
  <a href="#" data-bkgimg="link-2-bkg.jpg">Link 2</a>
</div>

I know this can be done with jQuery, but I prefer a vanilla JS solution if possible.

Answer №1

Take a look at this codepen

var link1 = document.getElementById("link1");
var div1 = document.getElementById("div1");

link1.addEventListener("mouseover", function( event ) { 
    var bg = event.target.dataset.bkgimg;
    div1.style.backgroundImage = 'url('+bg+')';
});

link1.addEventListener("mouseleave", function( event ) { 
    div1.style.backgroundImage = '';
});

This example code serves to demonstrate how to achieve a certain functionality. If you are accustomed to using JQuery but want to switch to vanilla.js, check out this resource:

Update: There are various ways to accomplish the same goal, but the key concept is to store background image links in data attributes, like data-bkgimg="link-2-bkg.jpg", and manipulate them on specific mouse events using JavaScript, such as mouseover.

Answer №2

If you want to accomplish this using vanilla JavaScript, you can simply select the element and add an event listener for the mouse event. Here's how you can do it:

var selectedElement = document.querySelector("#hoverItem");

selectedElement.addEventListener("mouseover", function(){
    selectedElement.style.backgroundImage = "url('http://lorempixel.com/output/nature-q-c-640-480-10.jpg')";
});

selectedElement.addEventListener("mouseout", function(){
    selectedElement.style.backgroundImage = "url('http://lorempixel.com/output/abstract-q-c-640-480-3.jpg')";
});

Check out a working example here:

https://jsbin.com/ceqiku/edit?html,js,output

Answer №3

To set or remove a background image, you can add the addEventListener directly to anchor tags or first add a class to the anchor tag and then add the event listener to it. Retrieve the value of data-bkgimg using getAttribute and manipulate the background-image accordingly.

var links = document.getElementsByTagName('a');

function setImage() {
  var bg = this.getAttribute('data-bkgimg');
  this.style.backgroundImage = "url(" + bg + ")";
}

function removeImage() {
  this.style.backgroundImage = "url('')";
}

for (var i = 0; i < links.length; i++) {
  links[i].addEventListener('mouseover', setImage, false);
  links[i].addEventListener('mouseout', removeImage, false);
}
a {
  padding: 30px;
  display: inline-block;
  background-size: cover;
}
<div class="background" style="background-image: url('link-1-bkg.jpg');">
  <a href="#" data-bkgimg="https://rlv.zcache.com/crash_test_dummy_marker_classic_round_sticker-r8b36e2d5c0f74a4c843565523094b867_v9wth_8byvr_324.jpg" class="is-active">Link 1</a>
  <a href="#" data-bkgimg="https://dummyimage.com/300.png/09f/fff">Link 2</a>
</div>

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

Utilize different versions of jQuery along with various plugins

I have integrated the AdminLTE Template into my project, which requires jQuery Version 3.X. Additionally, I am using the Flotchart jQuery library, which specifically needs jQuery Version 1.11.3. To handle this conflict, I have implemented the $.noConflic ...

Angular and Firefox are flagging the response from my OAuth call as incorrect, however, Fiddler is showing a different result

Currently, I am in the process of developing a Cordova application and require OAuth authentication with my Drupal backend. My main issue lies in obtaining a request token for this purpose. Despite receiving a 200 response indicating success, when inspecti ...

How is it possible for a local variable to be utilized outside of its original scope in code?

After obtaining a game demo from a website, I came across this particular code snippet: if(nx == food.x && ny == food.y) { var tail = {x: nx, y: ny}; score++; create_food(); } else { var tail = snake_array.pop(); tail.x = nx; ...

Progress bar displaying during Ajax request

I'm currently working on an Ajax request that uploads images to the Imgur API and I want to implement a progress bar to show users the upload progress. I found some guidance in this thread, but it seems to display only 1 and stop working. This is the ...

A plethora of options for popup modals in jQuery, including stacked modals and various alternative modal

Is there an alternative to using multiple modals? I require the ability to have multiple instances of modals. Upon clicking "Open modal" on the main page, a form modal (Modal-A) should open, with a link inside Modal-A that can open another modal (Modal-B) ...

Tips for updating checked checkboxes in a php mysql database

When submitting an HTML form with a selected checkbox, update the values of the selected checkboxes in a MySQL database. For example: update enquires set status = '2' where id in (selected checkbox values) View the screenshot of the checkbox Vi ...

Setting a default value in a dynamic dropdown using AngularJS

I could really use some assistance with my issue as I am fairly new to working with AngularJS. My dilemma is related to setting the default value in a select option when there is only one item available due to it being a dynamic select option. Though there ...

Detect changes in class properties using Node.js

Is it feasible to establish direct proxy watchers for class properties in Node.js? class User{ constructor(name){ this.name = name; let pObject = new Proxy(this,{ set: () => { console.log("something cha ...

Deactivate every checkbox in a row within an array

Seeking assistance with disabling a specific checkbox within a row. For example, Consider the following scenario {availableBendsHostnames?.map((bEnds, indx) => ( <div key={indx}> <div>B-End: {bEnds}</div> ...

Guide to showing an uploaded image in a child component using Vue.js

Using the v-file-input component from Vuetify, I am able to upload images with the following code: <v-file-input label="Image" filled accept="image/png, image/jpeg, image/bmp" prepend-icon="mdi-camera" v-mod ...

Learn how to customize the path for express.cookieSession based on the req.url in your application

I've developed a node.js server that utilizes passport for user authentication and express.cookieSession for session management. Currently, I have multiple clients, each with its own folder serving different copies of my application. The access to th ...

When populating data, two ID fields (_id and id) are generated as duplicates

Upon retrieving information from my database, I have noticed the presence of an additional id field alongside the standard _id field. These two fields consistently contain identical values. However, it seems that the id field appears only during population ...

What is the best way to progressively load sections of an HTML table?

I'm facing an issue with a table that is rebuilt asynchronously every time a new option is chosen from a dropdown. The HTML generation works fine, but sending it back across the wire breaks when the size is too large. One idea I had was to query sect ...

Saving table sorting in Redux with Ant Design Table

I am currently working with Antd Version 4.2.2 in my ReactJS project. Specifically, I am utilizing the Ant Design < Table /> component. My goal is to save the sorting order that is applied to the columns into Redux state. Here is my current approa ...

Angular 6 - implementing a dynamic carousel with bootstrap styling

I am currently working on a carousel using bootstrap4 where the images are sourced from an array. However, I am facing an issue where the first element must have the active class. <div id="carouselExampleFade" class="carousel slide carousel-fade" dat ...

Looking to target an element using a cssSelector. What is the best way to achieve this?

Below are the CSS Selector codes I am using: driver.findElement(By.cssSelector("button[class='btn-link'][data-sugg-technik='append_numbers']")).click(); driver.findElement(By.cssSelector("button[class='btn-link'][data-sugg- ...

Animating range tick movements as the range thumb moves

My custom range input includes a span that displays the range's value and a div with multiple p elements acting as ticks. To create these ticks, I had to use a custom div because using "appearance: none" on the range hides the ticks by default. The ti ...

Receiving a 404 error when attempting to use the 'import' statement within a script tag labeled as a module

I am currently working on a NodeJS project that utilizes Webpack for bundling and Express for serving. Whenever a user visits the root domain, they are served an index.html file containing a <script> block in the footer with a type of module. index. ...

jQuery UI Datepicker extending beyond its bounds

My Datepicker is expanding and filling the entire screen. What could be causing this issue? Here is my code: Additionally, how can I change the date format in jQuery to appear as dd-mm-yyyy? https://i.stack.imgur.com/IQzVV.png HTML: <!DOCTYPE html&g ...

Concealing overflow for text content through CSS styling

I am currently working with an element that contains both an image and text. View the Fiddle here Note: To see the full grid, resize the preview accordingly. The CSS I have written is as follows: .gridster .gs-w .item{ position: relative; wi ...