Home > front end >  Can't Inject Variable into Style Margins with Javascript
Can't Inject Variable into Style Margins with Javascript

Time:08-16

Fairly easy solution to this problem, I'm pretty sure, but I'm still currently unable to find where the problem may be (probably some syntax).

I'm trying to create a simple JS exercise to move an object's position to a random place after each hover/mouseover. (DOM manipulations fundamentals).

Here is the code:

let arr = [".top", ".left"];
let logTest = []

document.querySelectorAll('div').forEach(occurence => {
  occurence.addEventListener('mouseover', (e) => {
    for (let i = 0; i < 2; i  ) {
      var num = Math.floor((Math.random() * 100)   1);
      e.target.style[arr[i]] = num   "px";
      logTest[i] = num   "px";
    }
    console.log(logTest[0]   ", "   logTest[1]);
  });
});

Since the numbers are being generated and printed correctly to the console, I'm fairly sure that the problem has to be in line 9, where e.target.style[.left and .top] is not being able to be assigned to the random numbers.

CodePudding user response:

let arr = [".top", ".left"];

Don't use '.' dots for specifying the style. Directly use the style property name. Use this:

let arr = ["top", "left"];

And make sure to set position as relative, absolute or fixed for the div elements.

Here's a working example made using your script:

<style>
  .t {
    height: 50px;
    width: 50px;
    background: green;
    margin: 10px;

    position: relative;
  }
</style>

<h1>Hello</h1>

<div >e</div>
<div >f</div>
<script>
let arr = ["top", "left"];
let logTest = []

document.querySelectorAll('div').forEach(occurence => {
  occurence.addEventListener('mouseover', (e) => {
    for (let i = 0; i < 2; i  ) {
      var num = Math.floor((Math.random() * 100)   1);
      e.target.style[arr[i]] = num;
      logTest[i] = num;
    }
    console.log(logTest[0]   ", "   logTest[1]);
  });
});
</script>
  • Related