3

I started learning js recently and I have a question- i.e in this code-

<html>

<body>
  <button type="submit" id='1'>Click me!</button>
</body>
<script>
  function fun() {
    let x = Math.Random();
  }

  var x = document.getElementById('1');
  x.addEventListener("click", fun);
</script>

</html>

Do I get a different number every time I press the button? if not, why? Don't I call the function every time I press the button, and thus I generate a different number?

8
  • 4
    That's not going to work. That's going to produce errors, and do absolutely nothing. Commented Aug 9, 2019 at 6:33
  • Why? won't it generate a different number when I press the button? Commented Aug 9, 2019 at 6:36
  • 3
    Think about what the function's called, and think about what you're passing to addEventListener. Also, you're never using that random number. Commented Aug 9, 2019 at 6:37
  • 1
    "Do I get a different number every time I press the button?" S.O. has snippets, I just edited your question adding one. Try it, and appreciate the beautiful error. Commented Aug 9, 2019 at 6:37
  • 1
    I think he wanted to pass fun as callback not function Commented Aug 9, 2019 at 6:43

2 Answers 2

3

Math.Random(); is change to Math.random();

<html>

<body>
  <button type="submit" id='1'>Click me!</button>
  <p id="result"></p>
</body>
<script>
  var x = document.getElementById('1');
  x.addEventListener("click", function(){
    let x = Math.random();
    document.getElementById("result").innerHTML = x;
 });
</script>

</html>

Sign up to request clarification or add additional context in comments.

Comments

2

There are few problems with your code ,I have mentioned.

ID should begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). Though since HTML5,any non space character is allowed in Id.But its a good practice to have id something readable.

Moreover

you should pass the callback as function expression ,you are passing (function) which is a keyword

Third

Its Math.random() not Math.Random()

function fun() {
    let x = Math.random();
    console.log( x);
  }

  var x = document.getElementById('a1');
  x.addEventListener("click", fun); // you should pass the callback as function expression ,you are passing (function) which is a keyword
<html>

<body>
  <button type="submit" id='a1'>Click me!</button>
</body>


</html>

1 Comment

The restriction on ID is only for HTML4, in HTML5 any one non-space character is allowed. It is probably still a good idea to use a readable ID, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.