Multiple onload events

Last update by Elxis Team

Add multiple events on document load with elxLoadEvent function.

Since Elxis 4.1 Poseidon you can add multiple onload events by using the built-in elxLoadEvent javascript function. In this article we will see why using the elxLoadEvent is both important and required and how to use it.

The need for elxLoadEvent

Let's say you have a script that needs to be executed on document's load. For example we will alert a message when the page is fully loaded. We do that by adding the code below to the document's head section.

window.onload = function() { alert('Document loaded!'); }

In Elxis this task can be easily using the addScript method of the elxisDocument library.

$eDoc = eFactory::getDocument();
$eDoc->addScript('window.onload = function() { alert(\'Document loaded!\'); }');

Now, what if an other extension try to add an onload event the same way? The second onload event will overwrite the first one! So, the alert message "Document loaded!" will never be displayed. The first onload event will not be executed.

Only the last call of window.onload will be executed if you call it multiple times on the same page.

It is clear now that we need to bypass this problem, and Elxis 4.1 has a built-in solution for this, the elxLoadEvent function.


Usage of elxLoadEvent

The use of elxLoadEvent function is pretty simple. Just put the script you want to execute inside it and that's all.

elxLoadEvent('javascript function here to call on window load');

You can use the elxLoadEvent function unlimited times on the same page and be sure that all onload events will be executed just fine. Below you can see our previous example and some other onload calls.

$eDoc = eFactory::getDocument();
$eDoc->addScript('elxLoadEvent(function() { alert(\'Document loaded!\'); });');
$eDoc->addScript('elxLoadEvent(function() { alert(\'An other one!\'); });');
$eDoc->addScript('elxLoadEvent(somefunction());');
$eDoc->addScript('elxLoadEvent(myfunction(4, 3));');

You develop a module, a template, a plugin and you want add an onload event? Use elxLoadEvent, it will make sure your code will always work.



It has been read 9671 times

You are free to copy, distribute and transmit the articles in this site for non-commercial purposes.
Creative Commons 3.0