CSS recognizing Javascript variables within html, is it possible?

Asked

Viewed 294 times

3

For example, I have a script that picks up mouse coordinates:

 function posicaoMouse(ev){
        ev.preventDefault();
        var x = ev.clientX;
        var y = ev.clientY;
        console.log(x);
        console.log(y);
    }

And I would like the top and the left to be defined by the variables xand y of Function posicaoMouse, it is possible?
<span class="duvida" id="duvida2" style="position: absolute; top:'$x' left:'$y'"> teste </span>

  • 2

    With CSS, no. What you can do is change these values via JS, with element.style.top = y and element.style.left = x, for example.

  • I understood, there I define for example var teste= $("#teste"); and then I define how teste = element.style... That’s it??

1 answer

6


You can change the value of the element property by javascript:

let elem = documento.getElementById("duvida2");
function posicaoMouse(ev){
    ev.preventDefault();
    var x = ev.clientX;
    var y = ev.clientY;
    elem.style.top = x;
    elem.style.left = y;
    console.log(x);
    console.log(y);
}
  • 1

    Got it !!! Thank you very much for the explanation Lucas !

  • In 7 minutes I can accept the answer, again, thank you !

  • What would Let be in let elem??

  • let is similar to var, however is available only in the scope that is being declared, is ECMA6, browsers more new are already accepting.

  • I get it, thank you !!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.