Byron Smith
Byron Smith

Reputation: 607

Change the background image of an element

So I'm having some issues with creating a really simple function that's supposed to change the background image of a div element to match whatever image is being hovered upon by the mouse.

The HTML looks like

<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()">

That's just the div element I want to change, alongside one of the images. So our function is supposed to take in an image element as a parameter. But I'm having a lot of trouble accessing this image parameter's src attribute and using that in the .style.backgroundImage property.

My current code is:

function upDate(previewPic){
    var div_element = document.getElementById('image').innerHTML;
    var picurl = "url(previewPic.getAttribute('src'))"
    div_element.style.backgroundImage = "url(picurl)";
 }

And this gets me an error of Uncaught TypeError: Cannot set property 'backgroundImage' of undefined on my browser console. If you can tell, I'm trying to put the actual div object into a variable, then put the picture url into a variable. Then I want to use the .style.backgroundImage property. This isn't working. But the solution is probably really simple. What could I do to fix it?

Upvotes: 0

Views: 1099

Answers (2)

JustALittleBit
JustALittleBit

Reputation: 53

If I understand on some image hover you want to change div background? I would do it with jquery:

$('img').hover(function(){

$('div').css(''background-image:'url("image_link")');

});

Upvotes: -1

Jacques
Jacques

Reputation: 3774

There are multiple issues with your code.

  1. Getting the inner html is just setting your variable to a string representation of what's inside the element, which is nothing since it's an <img> tag.
  2. Essentially, you're putting everything in quotes, so javascript doesn't do anything with it.

Remove the .innerHTML from the first line of the function, and then take the parts javascript needs to evaluate as code out of the quotes.

Change your code to:

function upDate(previewPic){
    var div_element = document.getElementById('image');
    var picurl = "url(" + previewPic.getAttribute('src') +")"
    div_element.style.backgroundImage = picurl;
}

This should work.

Upvotes: 2

Related Questions