Changing the background image of a specific div using CSS and JavaScript: a beginner's guide

I've been attempting to modify the background of a div in HTML using JS and CSS. Below is the code I've tried, but it doesn't seem to be working as expected.

function changeBackground(previewPic)
{
  var imgUrl = previewPic.src;
  console.log(imgUrl);
  x = document.getElementById('image');
  document.getElementById('1').style.backgroundImage = previewPic.src;
}
body{
    margin: 2%;
    border: 1px solid black;
    background-color: #b3b3b3;
}
.image{
    line-height:650px;
    width: 575px;
    height: 650px;
    border:5px solid black;
    margin:0 auto;
    background-color: #8e68ff;
    background-image: url('');
    background-repeat: no-repeat;
    color:#FFFFFF;
    text-align: center;
    background-size: 100%;
    margin-bottom:25px;
    font-size: 150%;
}
.preview{
    width:10%;
    margin-left:17%;
    border: 10px solid black;
}
img{
    width:95%;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Photo Gallery</title>
  <link rel="stylesheet" href="css/style.css">
  <script src = "js/gallery.js"></script>
</head>
<body>

  <div class="image" id = "1">
    Hover over an image below to display here.
  </div>

  <img class = "preview" alt = "Styling with a Bandana" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover = "changeBackground(this)" onmouseout = "resetBackground()">

  <img class = "preview" alt = "With My Boy" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG" onmouseover = "changeBackground(this)" onmouseout = "resetBackground()">

  <img class = "preview" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg" alt = "Young Puppy" onmouseover = "changeBackground(this)" onmouseout = "resetBackground()">

</body>
</html>

This function retrieves the image source URL and stores it in the 'imgUrl' variable. However, despite logging the URL correctly, the background update is not functioning as intended.

Answer №1

You are missing the ability to revert back using the function - unDo().

var obj;

function upDate(previewPic) {
    document.getElementById("image").innerHTML = previewPic.alt;
    document.getElementById("image").style.background = "url('" + previewPic.src + "')";
}

function unDo() {
    var oldAlt = "Hover over an image below to display here.";
    document.getElementById("image").innerHTML = oldAlt;
    document.getElementById("image").style.background = "#8e68ff";
    document.getElementById("image").style.backgroundImage = "url('')";
}
body {
    margin: 2%;
    border: 1px solid black;
    background-color: #b3b3b3;
}

#image {
    line-height: 650px;
    width: 575px;
    height: 650px;
    border: 5px solid black;
    margin: 0 auto;
    background-color: #8e68ff;
    background-image: url("");
    background-repeat: no-repeat;
    color: #ffffff;
    text-align: center;
    background-size: 100%;
    margin-bottom: 25px;
    font-size: 150%;
}

.preview {
    width: 10%;
    margin-left: 17%;
    border: 10px solid black;
}

img {
    width: 95%;
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Photo Gallery</title>
        <link rel="stylesheet" href="css/gallery.css" />
        <script src="js/gallery.js"></script>
    </head>
    <body>
        <div id="image">
            Hover over an image below to display here.
        </div>
        <img class="preview" alt="Styling with a Bandana" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover="upDate(this)" onmouseout="unDo()" />
        <img class="preview" alt="With My Boy" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG" onmouseover="upDate(this)" onmouseout="unDo()" />
        <img class="preview" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg" alt="Young Puppy" onmouseover="upDate(this)" onmouseout="unDo()" />
    </body>
</html>

Answer №2

Change the identifier from numeric to alphabetic and give it another shot.

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

Having trouble with generic typescript props in React? It seems like typescript generic props are not functioning as expected. Let's explore

In my React project, I am facing a challenge. I have a functional component where I pass down a single prop: <TableComponent tableStateProp={tableState} /> The `tableState` is a state hook declared in the parent component like this: const [tableSt ...

Using JQuery to extract information from a string with HTML tags

Surprised that this particular question didn't appear in the list of related questions. While there are some similar topics, I am specifically interested in finding out: string s = "<p>Cats</p><div id='fishbiscuits'>myValu ...

Issues with HTML2PDF image rendering limitations

I'm encountering an issue where the image tag is not working with the following HTML code being displayed in a PDF: $html.= "<h2>Header</h2>\n"; $html.= "<p>Text</p>\n"; $html.= "<img src=" . $path1 ."> ...

Creating a promotional slide-up feature on a website page using jQuery and Bootstrap

Is there a way to achieve a promotional slide-up similar to the one showcased below using the features provided by Bootstrap/jQuery? https://i.sstatic.net/ZMLeD.png ...

Having trouble with setting the date in Firefox 57 using Selenium 3.4?

Date Field Image Having trouble setting date information beyond the specified date field using the sendKeys function. Attempted to use JavaScript but unable to successfully set the value. Update: HTML driver.findElementBy("//label[text()='Past Spe ...

Pass the output from the Unirest Node get request function to be displayed in the Jade view

I'm currently in the midst of developing my very first Node application, and I've hit a snag with unirest.get requests. My project features Node, Express, as well as the Act On API. To speed up the setup process, I've opted to use the expre ...

Is there a way to adjust the size of the canvas element in HTML without compromising quality or resorting to zooming?

I'm currently working on a basic modeling application for the web. The main component of my app is a canvas element that I'm trying to size correctly. However, when I set the height and width using CSS, it scales the entire canvas and compromises ...

What modifications were implemented in Bootstrap 5 to cause controls to automatically assume their maximum size?

After upgrading NodeJs to version 16.13.0 from 14.x, one of the modules that was updated was bootstrap. This caused me to remove my Jumbotron control due to the upgrade, although I don't believe that is directly related to the issue I am experiencing. ...

Restrict printing loops within the designated division layer

Is there a way to limit the number of rows displayed horizontally when using foreach? I only want to display 7 rows. Can this be achieved with CSS or pagination? Here is an image illustrating the issue: https://i.sstatic.net/yJx3N.png Currently, it print ...

What is the process by which a web browser executes a ".jsx" file while in development?

As a beginner in the world of react, I have successfully been able to execute the dev and build tests. One question that has been boggling my mind is how browsers handle ".js" files. I know that when a project is build, the browser runs the &quo ...

The default page length for datatables cannot be applied at this time

I am having trouble with setting the pageLength for a table in this code. Can someone assist me with this issue? $(document).ready( function () { $('#Campaign_Overview').DataTable({ "pageLength": 5, "lengthMenu": [5, 10, 25, 50] }); ...

Ways to show notifications multiple times depending on the number of items in a list

My task is to show banner messages on the user interface based on the number of items in a list. In my _Layout file, I called my partial view like this: @Html.Partial("~/_Notification.cshtml") The content of _Notification.cshtml: <div id="outage- ...

Accessing store state in axios plugin with Nuxt.js

I've encountered a problem where I have a token stored, but I'm struggling to access it in my axios plugin while using Nuxt.js. In the past with just Vue, it was simple to import the store and access the token. However, I'm having difficulty ...

Creating an event listener in the window object for the three.js

Struggling to create a MyObject.prototype.onWindowResize function for scaling a simple cube on window resize. Can't seem to make it work - either getting undefined or no change at all. Spent hours searching for a solution with no luck. Any help would ...

Encountering an issue while executing grunt-contrib-imagemin

Encountering a permissions issue while attempting to execute the grunt-contrib-imagemin script. The installation of grunt-contrib-imagemin was done as follows: npm install --save-dev grunt-contrib-imagemin Node and npm are both installed in my local user ...

What is the best way to navigate back to the previous state in reactjs?

I have implemented a sidebar component with its initial state set to false in order to hide the block until a user interacts with the hamburger icon. Once clicked, the state changes to true and displays the sidebar menu. However, I am facing an issue whe ...

Setting the hex color of a material in Three.js using material.color.setHex with a Mesh

My code is configured to change the colors of certain objects based on different conditions. Currently, it utilizes loops like for (j = 0; j < objects[i].children.length; j++) { objects[i].children[j].material.color.setHex(0x1A75FF); } to update t ...

Using angularjs to include content from other files is known as

As I delve into the concept of creating directives in AngularJS, I am faced with the imminent end of Angular 1.x and the rise of Angular 2.x. The shift seems daunting, but I am determined to bridge this gap seamlessly. In my quest for clarity, I stumbled ...

The success callback in JQuery Ajax does not function properly when constructing an array of Ajax calls

I am facing a challenge in building an array of custom objects by resolving promises from an array created based on another array. Consider having an array of letters = ['a', 'b', 'c']. I then map this array to make Ajax call ...

json How to retrieve the first index value in jQuery

As part of my Ajax loop, I am successfully generating JSON and iterating through the results. My goal is to extract only the first index value of JSON which is name. In jQuery, I have the following code: PHP $jsonRows[] = array( "name" => ...