-1

I'm trying yo change the background of a DIV, and I think that my code is correct, but it seems no. I think the error is on the URL parameter because without parameter the function works.

This is my code:

<script language="JavaScript">
        function imagen(col){
        document.write(col);
        var elem = document.getElementById("fondo");
        elem.style.backgroundImage = url('col');

        }
    </script>

<div class="grid-block" id="fondo" width: 100%; height: 100vh;">
        <div class="heading">
        <a href="pagina1.html" onMouseOver="imagen(uploads/banner-01.jpg)" >Rojo</a>
        </div>
    </div>

Thank you.

1 Answers1

1

The argument to imagen() needs to be in quotes. Otherwise it will be evaluated as an expression, and you'll get a syntax error.

You need to use string concatenation to combine the argument with url().

Don't use document.write() in functions that run after the DOM is loaded. It will clear the DOM -- see Why is document.write considered a "bad practice"? Use console.log() for debugging output.

function imagen(col) {
  console.log(col);
  var elem = document.getElementById("fondo");
  elem.style.backgroundImage = 'url(' + col + ')'
}
<div class="grid-block" id="fondo" width: 100%; height: 100vh; ">
    <div class="heading ">
    <a href="pagina1.html " onMouseOver="imagen('uploads/banner-01.jpg') " >Rojo</a>
    </div>
</div>
Barmar
  • 596,455
  • 48
  • 393
  • 495