Pass variable to this.src

I have the name of an image file generated in javascript and passed to the src of an image in HTML – this currently works.

I want to pass another image file as the onmouseover attribute of the image.
(because my file name is dynamically generated I can’t use hover in css).

        var new_source_for_image = "/prestashop_1.7.0.3/modules/se_daynight/img/" + file_name + ".png";

<div id="visit_daynight">
    <div class="change_visit">
        <a target="_blank" rel="nofollow" href="#"><img id="visit_image" src="" width="350" height="350"></a>

So i thought of adding another variable from a generated file name:

var new_source_for_image_with_glow = "/prestashop_1.7.0.3/modules/se_daynight/img/" + file_name + "_glow" + ".png";


<a target="_blank" rel="nofollow" href="#"><img id="visit_image" src="" width="350" height="350" 

But I don’t know how to pass my new variable in the this.src attribute.

Anybody have any ideas?

Much appreciated!

With jQuery by using mouseover() and mouseout() and attr() methods.

  var file_name='your_file_name';
  var new_source_for_image ="/prestashop_1.7.0.3/modules/se_daynight/img/" + file_name + ".png";
  var new_source_for_image_with_glow = "/prestashop_1.7.0.3/modules/se_daynight/img/" + file_name + "_glow" + ".png";



I believe this is what you’re looking for. No jQuery required just plain old JavaScript.

const image = document.querySelector('img');

const baseImagePath = '';

const mouseEnterImage = '300';

const mouseLeaveImage = '400';

const replaceImage = (withImg) => {
    image.src = `${baseImagePath}${withImg}`;

document.addEventListener('mouseenter', () => replaceImage(mouseEnterImage));

document.addEventListener('mouseleave', () => replaceImage(mouseLeaveImage));

Here is a fiddle of it working:

Hope this helps.

the better way to use these event handlers, onmouseover & onmouseout is to supply them with their respective functions defined inside the your script. And you also need to properly assign the image to img element (ev.srcElement) Have a look:

MouseOverHandler = function(ev){ 
    ev.srcElement.src = new_source_for_image
    console.log('should change',ev);

MouseOutHandler = function(ev){ 
    ev.srcElement.src = old_source_for_image
    console.log('should change',ev);

<a target="_blank" rel="nofollow" href="#"><img id="visit_image" src="" width="350" height="350" 

this will work:

        var new_source_for_image_with_glow = "testA.png";

        var anotherSrc = "testB.png";

        function onmouseoverFunc(element) {
            element.src = new_source_for_image_with_glow;

        function onmouseoutFunc(element) {
            element.src = anotherSrc;

<a target="_blank" rel="nofollow" href="#">
    <img id="visit_image" src="new_source_for_image_with_glow" width="350" height="350"

If you can dynamically set a src… I suppose you also can set a data attribute for an “alternate source” ?!?

This demo interchanges the URL between “sports” and “animals”.