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

Trouble with an external .js script

function displayMessage() { var isConfirmed = confirm("Do you want to proceed?"); if (isConfirmed) { window.location = "./proceed"; } }; function checkIfEmpty(){ console.log("checkIfEmpty"); }; @CHARSET "ISO-8859-1"; form { margin:0 auto; width:300px ...

Sleek descending motion effect

I have created a simple function, but it is not animating smoothly and seems to lag... I am using it for a div sized at 1600x700 pixels on page load $(document).ready(function(){ $('#slider').slideDown(500); }); Is there any way to ensure s ...

How can we effectively transform an HTML opening and closing tag into a function?

Dealing with a complex HTML tag can be challenging, especially when it appears in various parts of the code. For instance: <div class="blabla" data-test="blablabla" ... data-another-attribute="blabla" > <some complex html code ... > </ ...

Responsive on Mobile Devices

I'm seeking assistance in brainstorming a creative idea or method to convert the carousel indicators into a menu, or any alternative approach to ensure the entire section is mobile responsive while keeping all the indicators visible within the mobile ...

Is there a way to identify if a user originated from a Google ad and determine if this is their nth page during the session using JavaScript code?

Is there a way for me to execute specific logic when a user, who arrived at the page via a contextual advertisement, reaches a certain page during their session? How can I make this happen? ...

Is there a way to load the right amount of images in advance, depending on the size of the

I'm currently trying to optimize the loading of Largest Contentful Paint (LCP) candidate images based on device size, but I'm encountering difficulties. The issue at hand: On smaller screens, only one image is displayed in a carousel On larger ...

creating an interactive element that seamlessly integrates with a dynamic background image slideshow

Struggling to make this work correctly as a newbie in javascript. I need the background image to slide upon hover and stay active on its selected div when clicked. The html, css, and javascript I have currently work fine - when the user clicks on a div, a ...

JavaScript Recursive Function for Generating FancyTree JSON Structure

I'm currently building an array of JSON objects for FancyTree (https://github.com/mar10/fancytree/wiki/TutorialLoadData). My JSON source is from the Jira REST service, and its structure can vary widely. Therefore, the code to construct the array of JS ...

When I decide to incorporate both BootstrapVue and Vuetify CSS frameworks into a single project

Can I incorporate two CSS frameworks into my current Nuxt.js project? Does anyone have any insight on why it might be beneficial to use two different CSS frameworks in a Vue.js project? Please provide some guidance on this matter. I am looking to optimize ...

Setting up Scss and purgeCss configuration in Next.js custom postCSS configuration: A step-by-step guide

My current project is using Scss in combination with Bootstrap for design. I have implemented purgeCss to remove unused Css, and customized my postcss.config.js file as follows: module.exports = { plugins: [ "postcss-flexbugs-fixes", [ " ...

Modifying the appearance of InputText through CSS encapsulation

I'm a newbie to using Blazor and I'm currently experimenting with changing the style of InputText by utilizing css isolation. Interestingly, I've managed to successfully change the style when setting it inline or internally, however, things ...

What is the best way to adjust a horizontal list of inline elements to stack vertically when the div container is resized?

Here is the issue I'm facing (notice how the yellow tiles are overflowing): (view image here) because my reputation points are not enough. The screenshot above illustrates how the small yellow rectangles are extending beyond the boundaries of the gr ...

What are the steps to integrate Webpack into an EJS Reactjs Express MongoDb application?

I have incorporated EJS, Express/NodeJs, and MongoDB into the project, along with ReactJs as an addition. My next step is to introduce Webpack for bundling both EJS and ReactJs files together. Although the end goal is to transition the p ...

Unable to locate module: '@material-ui/pickers' - Material UI React

I encountered an error that said: Material UI React - Module not found: Can't resolve '@material-ui/pickers' in React. Previously, I faced a similar issue with '@date-io/date-fns' but was able to fix it by updating to the latest ...

When utilizing the "as" attribute, styled components do not inherit any styles

I am currently utilizing both styled-system and styled components, working on a simple scenario like the one below: const buttonFont = { fontFamily: "Chilanka" }; // define basic text styling const Text = styled.div` ${typography} ${color} `; // c ...

Manipulate a deeply nested JSON object in JavaScript by iterating through it and constructing a new data

Struggling to rearrange complex JSON data (data1) into a more organized format (data2). Progress has been slow. data1 is created by scanning a parent directory (recipes) for html files. data2 is the desired output structure using data1, where content wit ...

Take action once the Promise outside of the then block has been successfully completed

Presented below is the code snippet: function getPromise():Promise<any> { let p = new Promise<any>((resolve, reject) => { //some logical resolve(data); }); p.finally(()=>{ //I want do something when ou ...

Error message: "jQuery Ajax CORS request returning undefined value"

I am delving into the world of cross-domain Ajax requests for the first time by interacting with an API. Utilizing jQuery, I aim to extract specific elements from the response and display them on the webpage. Here is the code snippet for the request: $.a ...

What is the reason for the value of an object's key becoming undefined when it is set within a loop?

I've always wondered why setting a certain object's key as its own value in a loop results in undefined. Take this code block, for example: var text = 'this is my example text', obj = {}, words = text.split(' '); for (i = ...

Having trouble retrieving the tag name, it seems to be giving me some difficulty

I have two separate web pages, one called mouth.html and the other nose.html. I want to retrieve a name from mouth.html and display it on nose.html when a user visits that page. How can I accomplish this using JavaScript? Here is the code snippet from mou ...