Home > Software design >  Why can I only change the CSS style through JS only once?
Why can I only change the CSS style through JS only once?

Time:01-19

Just start to learn JS. I wanna change the fontSize randomly every time I click the button, but it only work the first time I click.

var oBox = document.querySelector('#box');
var randomNumber = ((Math.random() * 10) * 10).toString();
var b = document.querySelector('#button');

b.addEventListener('click', function () {
    oBox.style.fontSize = randomNumber   'px';
})

CodePudding user response:

Because you are only generating the random number once. You need to either make a function to generate a different random number every time it's called, like this:

var oBox = document.querySelector('#box');
var b = document.querySelector('#button');

function getRandomNumber() {
  return ((Math.random() * 10) * 10).toString();
}

b.addEventListener('click', function () {
    oBox.style.fontSize = getRandomNumber()   'px';
})
<div id="box">
  This is a test
</div>

<button id="button">
Button
</button>

Or to generate it directly in the click event, like this:

var oBox = document.querySelector('#box');
var b = document.querySelector('#button');

b.addEventListener('click', function () {
    const randomNumber = ((Math.random() * 10) * 10).toString();
    oBox.style.fontSize = randomNumber   'px';
})
<div id="box">
  This is a test
</div>

<button id="button">
Button
</button>

CodePudding user response:

The line var randomNumber = ((Math.random() * 10) * 10).toString(); is executed only once. Therefore, you should use a constant: const randomNumber = ((Math.random() * 10) * 10).toString();.

In your case you have to move this line inside the function. After that, the line will be executed after every click event:

const box = document.querySelector('#box');
const button = document.querySelector('#button');

button.addEventListener('click', function () {
    const randomNumber = ((Math.random() * 10) * 10).toString();
    box.style.fontSize = randomNumber   'px';
});
<div id="box">Hello World</div>
<button id="button">Button</button>

You should also give your JavaScript variables meaningful names. Just b is not a good name for more complex software. Also take a look in the documentation for the difference between let, var, and const.

  • Related