0

while calling a function in javascript , we generally call it by myFunction() ,(myFunction is a random function) but in the code given below btn.onclick=bgChange is given without () , how is that possible ? Should'nt it return function description instead?

  var btn = document.querySelector('button');
  function random(number) {
    return Math.floor(Math.random()*number);
  }
  function bgChange() {
    var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
    document.body.style.backgroundColor = rndCol;
  }
  btn.onclick = bgChange;

Himanshu Jotwani
  • 378
  • 2
  • 16
  • 1
    That is called a callback function, it is actually invoked when the onclick function is triggered. It says let btn.onclick point to that function and execute it. – Zach M. Oct 09 '18 at 17:34

1 Answers1

2

btn.onclick = bgChange; doesn't call function, it adds click handler (callback). When user clicks on button, it will invoked: btn.onclick(); - your handler stored in btn.onclick property will be called. In your case it will be the same as call bgChange();

ingvar
  • 4,169
  • 4
  • 16
  • 29
  • but how it is the same , I read the tagged question too but if I define a function like we use () at the end , here we aren't – Himanshu Jotwani Oct 09 '18 at 17:51
  • in `` value of `onclick` attribute isn't handler, it's JS script called after click. `btn.onclick = bgChange;` === `onclick="bgChange();">Click me` – ingvar Oct 09 '18 at 17:53
  • See https://www.w3schools.com/jsref/event_onclick.asp for more info – ingvar Oct 09 '18 at 17:54
  • see this

    Click me to change my text color.

    here it is called by myFunction()
    – Himanshu Jotwani Oct 09 '18 at 17:57
  • here it isn't

    This example demonstrates how to assign an "onclick" event to the window object.

    Click anywhere in this window to change the background color of body.

    – Himanshu Jotwani Oct 09 '18 at 17:58
  • As I said before - in JS you set handler, in HTML you set js script which will be called after click. This script can be random, not just function call, e g `onclick="myFunction(); myFunction();"` will be valid – ingvar Oct 09 '18 at 18:00
  • could you please please elaborate I'm kinda stuck on it since 2 days – Himanshu Jotwani Oct 09 '18 at 18:02
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/181567/discussion-between-ingvar-and-himanshu-jotwani). – ingvar Oct 09 '18 at 18:03