Search code examples
javascriptthissrc

How can I change image source in javascript using "this"?


I have a div element with id = "image" having no background-image initially. I have an another image, on which when I hover, somefunction(this) is called. Now, I want this function to change that div's background image to the hovered image. I am doing something like this...

HTML:

<div id = "image"> a division </div>
<img class = "abc" onmouseover = somefunction(this) src ="someimage.jpg>

CSS:

#image{ background-image : url(''); }

JS:

function somefunction(element)
{
    var x = document.getElementById('image');
    x.style.background.src = element.src;
}

But It's not working anyway, and I want to do this using "this" only.


Solution

  • Try this code

    function somefunction(element)
    	{
    		var x = document.getElementById('image');
    		x.style.backgroundImage = "url('"+element.src+"')"
    	}
    	<div id = "image"> a division </div>
    	<img class = "abc" onmouseover="somefunction(this);" src="your path to file.PNG"/>