Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript addEventListener function

I am new to Event Handlers and I have come across a code that is written below

document.addEventListener("DOMContentLoaded", function() {
    initialiseMediaPlayer();
}, false);

Is there any difference in writing the same code as

document.addEventListener("DOMContentLoaded", initialiseMediaPlayer();, false);

Ultimately we are calling the same function, so does it make a difference or is there some advantage in writing it in the manner above?

like image 533
Bazinga777 Avatar asked Mar 06 '13 19:03

Bazinga777


1 Answers

document.addEventListener("DOMContentLoaded", function() {
    initialiseMediaPlayer();
}, false);

Will execute initialiseMediaPlayer when the dom content is loaded.

document.addEventListener("DOMContentLoaded", initialiseMediaPlayer();, false);

is a syntax error; if you remove the semicolon:

document.addEventListener("DOMContentLoaded", initialiseMediaPlayer(), false);

calls initialiseMediaPlayer immediately, then passes the return value (which likely isn't a function) to addEventListener. This won't act as desired.


You can do

    document.addEventListener("DOMContentLoaded", initialiseMediaPlayer, false);

(remove the parentheses = function call). Then initialiseMediaPlayer will be executed on dom content loaded, and act as desired.

However, unlike in the former case, initialiseMediaPlayer will actually receive the arguments given by the browser. Also, its return value is received by the browser. In case of DOMContentLoaded, most likely this doesn't matter much.

You also avoid creating one extra anonymous function if you pass initialiseMediaPlayer directly. Again, the effect is not really perceptible from the user's standpoint.

like image 98
John Dvorak Avatar answered Oct 04 '22 15:10

John Dvorak