Update the background URL of a div element using an HTML tag

My question is about a CSS div with set dimensions and background that I want to change on hover.

I am aware that this seems like a simple task, but what I really want to do is retrieve the background sources from within the HTML tag itself.

For example:

<div class="somediv" data-imgbefore="img1.png" data-imgafter="img2.png"></div>

If anyone could assist me with this query, I would greatly appreciate it.

Answer №1

To achieve the desired effect without using jQuery, you can utilize basic Event Listeners. Check out this example: https://jsfiddle.net/gnu9utos/3/

// Identify the element to interact with
var element = document.querySelector('.somediv');

// If we successfully get the element from the document
if(element) {
    var before = element.getAttribute('data-imgbefore');
    var after = element.getAttribute('data-imgafter');

    if(before && after) {
        element.style.background = 'url(' + before + ')'; // Set initial state

        // Event listener for mouseover
        element.addEventListener('mouseover', function(event) {
            element.style.background = 'url(' + after + ')';
        });

        // Event listener for mouseout
        element.addEventListener('mouseout', function(event) {
            element.style.background = 'url(' + before + ')'; 
        });
    }
}

You may consider adding a check for mouseleave to restore the image to its original state and applying some CSS styles.

I trust this information proves useful to you.

Answer №2

Try out this simple JQ code snippet to achieve the desired effect

While it may not be the most optimal solution, it gets the job done. I included a background-color for demonstration purposes, which can be removed leaving only the background-image

Check out the implementation on this JsFiddle link

This script creates two variables and assigns them to each image (before and after img) within div elements with the class name .somediv

An initial background-image is added to the div element

Upon hover, the background-image of the div toggles between imgbefore and imgafter

JQuery Code:

$(".somediv").each(function(){  

  var imgbef = $(this).data("imgbefore"),
      imgaft = $(this).data("imgafter")
  $(this).css({'background-image': 'url(' + imgbef + ')','background-color':'red'});

  $(this).hover(function(){

     $(this).css({'background-image': 'url(' + imgaft + ') ','background-color':'blue'});
  }, function(){
     $(this).css({'background-image': 'url(' + imgbef + ')','background-color':'red'});
  });

});

HTML Structure:

<div class="somediv" data-imgbefore="img1.png" data-imgafter="img2.png"></div>

CSS Styling:

.somediv {
   height:250px;
   width:70%;  
 }

Feel free to reach out if you have any questions or need further assistance

Answer №3

To achieve this effect, utilize JavaScript. Additionally, you can incorporate an onmouseleave function and pass this.dataset.imgbefore as the second argument.

changebg = function(el, img) {
var bg = "url("+img+")";
el.style.backgroundImage = bg;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="somediv" id="mydiv" data-imgbefore="http://lorempixel.com/400/200/sports" data-imgafter="http://lorempixel.com/400/200/animals" onmouseover="changebg(this, this.dataset.imgafter)">Lorem</div>
</body>
</html>

Answer №4

If you want to customize the appearance of your div elements, simply update the data-imgbefore and data-imgafter attributes!

$(document).ready(function(){

$('.somediv').each(function( index, value ) {
var img = $(this).attr('data-imgbefore');
$('.somediv').css({'background-image':'url('+ img +')', 'background-size':'200px 200px'});
});

//$('.somedive').css({'background-image':'url("http://www.palladio-tv.it/Internet/siti_gec/2B/Manzan_Disney/codice/Pippo.png")', 'background-size':'200px 200px'});

$('.somediv').hover(

function () {
var img = $(this).attr('data-imgafter');
$(this).css({'background-image':'url('+ img +')', 'background-size':'200px 200px'});
}, 

function () {
var img = $(this).attr('data-imgbefore');
$(this).css({'background-image':'url('+ img +')', 'background-size':'200px 200px'});
}
);
});
.somediv {width:200px;height:200px;border:1px solid #F2F2F2;border-radius:4px;display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<div class="somediv" data-imgbefore="http://www.palladio-tv.it/Internet/siti_gec/2B/Manzan_Disney/codice/Pippo.png" data-imgafter="http://www.filastrocche.it/contenuti/wp-content/uploads/2001/04/pippogoofy_352.jpg"></div>
<div class="somediv" data-imgbefore="http://www.palladio-tv.it/Internet/siti_gec/2B/Manzan_Disney/codice/Pippo.png" data-imgafter="http://www.filastrocche.it/contenuti/wp-content/uploads/2001/04/pippogoofy_352.jpg"></div>

Cheers!!!

Answer №5

It seems like you may be struggling to achieve your goal. Have you considered ditching the HTML tag requirement and experimenting with CSS :hover instead?

#somediv {
    background: url(...);
}

#somediv:hover {
    background: url(...); /* try a different URL */
}

Visit this link for more information on CSS background properties.

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

Creating a circular frame for your image to use as a Facebook profile picture

In the process of developing an input feature that allows users to upload file images for avatar changes, similar to Facebook's functionality. However, I am aware that Facebook utilizes a circular area for avatars and enables users to adjust the image ...

Utilize AJAX to showcase JSON data retrieved from a specified URL

We are striving to showcase the names listed in our JSON file within a div using JavaScript. Despite multiple attempts, we have not yet achieved success. JSON data: This is the approach we took: <button>fetch data</button> <div id="result ...

Guidelines for placing an HTML element in relation to another HTML element using CSS or JavaScript

Is there a way to position an HTML element in relation to another using CSS or JavaScript? I have attempted to copy the inner HTML of the "second-element" and append it inside the "first-element", but this approach is causing issues with other functional ...

Adjusting the size of text in KineticJS to ensure it fits comfortably within a rectangle while

Check out this link: http://jsfiddle.net/6VRxE/11/ Looking for a way to dynamically adjust text, text size, and padding to fit inside a rectangle and be vertically aligned? Here's the code snippet: var messageText = new Kinetic.Text({ x: .25* ...

Electron experiences a crash while attempting to execute an HTTPS request within an addeventlistener callback function

In the process of creating a simple Electron application that facilitates user login into a system, I encounter an issue. The app collects the username and password entered by the user through form text inputs. Upon clicking the "login" button, the program ...

Nextjs: where all roads lead back to the homepage

Having an issue in my app where all redirects keep leading back to the homepage. The problem seems to stem from my Navbar.js component, as shown below. Despite adding the required route in the Link tag for next-js, both client and server compilation is suc ...

What is the best way to make the children of a parent div focusable without including the grandchildren divs in the focus?

I want to ensure that only the children of the main div are able to receive focus, not the grandchildren. Here is an example: <div class="parent" > <div class="child1" > <!-- should be focused--> <div class="g ...

What is the best way to display a popup window on top of the parent window?

How can I display a popup window on top of the parent window when a button is clicked? I have tried using the Window.Focus() method, but the popup window keeps going back behind the parent window. I would greatly appreciate any help on this. Thank you in ...

Owl carousel issue: Fixed position not functioning properly

To view the page with the issue, click here I am attempting to make the column (div) day/date headers sticky when they scroll out of view so that users can always see what day they are looking at. Instead of directly manipulating the header itself, I have ...

Experiencing Issues with the Email Button Functionality on My Website

I am looking to create an "Email" button that will send the user-entered text to my email address. Here is the code snippet: <form method="post" action="malto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cb ...

The onclick event is malfunctioning in Chrome when dealing with data driven by SQL

<select id='city' name='city' > <?php $dbcon = mysql_connect($host, $username, $password); mysql_select_db($db_name,$dbcon) or die( "Unable to select database"); $city_query = "SELECT city,county FROM citycatalog order by city ...

Is there a way to ensure that the 'pointermove' event continues to trigger even after the dialog element has been closed?

I am working on a project that involves allowing users to drag elements from a modal dialog and drop them onto the page. I have implemented a feature where dialog.close() is called once the user starts dragging. This functionality works perfectly on deskto ...

Can you tell me the appropriate type for handling file input events?

Using Vue, I have a simple file input with a change listener that triggers the function below <script setup lang="ts"> function handleSelectedFiles(event: Event) { const fileInputElement = event.target as HTMLInputElement; if (!fileInp ...

Locate a JQuery element within another JQuery element

Apologies for my poor grasp of English. I am working with HTML and JavaScript. <noindex> <h1>This is h1 in noindex</h1> <div> <h1>This is h1 in noindex and in div</h1> <div> <h1>This is h1 in noindex a ...

Styling Page Titles with CSS Content

I'm having trouble including the page title in the footer of all printed pages. I've tried using the following code snippet: @page { @bottom-right { content: attr(title); } } However, this method doesn't seem to be working for me. ...

Execute `preventDefault` prior to authenticating the User with Dev

In my index, I have a modal with a user sign-up form. I created a JavaScript function that triggers when the "Save" button is clicked. If users encounter errors, alerts appear in the modal but it redirects to another page. I want the page to stay on the c ...

Updating Google+ url parameter dynamically without the need to reload the page

Is there a way for a user to share a link on social media platforms like Facebook and Google+ without having to refresh the page? The user can customize the link with an ajax call, ensuring that the page remains static. Here is my code for the Google Plu ...

Troubleshooting: React Native and OneSignal notifications not showing up

Currently, I am developing an app in React Native and working on integrating notifications with OneSignal. Although I am able to efficiently receive notifications, I do not want them to be displayed on the screen when they are received. I came across a ` ...

Can you show me the method to import these ES6 exports? Are they specifically named exports or the default?

As I reviewed the code in the Material UI project, I came across a section that is exporting a variety of React Components: src/Dialog/index.js: export { default } from './Dialog'; export { default as DialogActions } from './DialogActions ...

Retrieve the node environment variable within a JavaScript file

When setting the env variable in the start command within the package.json file, here is an example: package.json "scripts": { "start": "webpack-dev-server --config ./webpack.config.config.dev.js --env.mode=dev --port 4200&quo ...