I would like to execute a JavaScript function after the page was loaded. At the moment I have a commandButton and everything works fine. However it would be more comfortable if the user is not supposed to hit the button.
I have tried f:event, but I do not have a listener, I have only the JavaScript function. Moreover body onload does not work for me as I use only high level components.
<f:view xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:pm="http://primefaces.org/mobile" contentType="text/html">
<ui:composition template="/resources/master.xhtml">
<ui:define name="content">
<pm:content>
<h:inputHidden id="address" value="#{pathFinderBean.address}" />
<div id="map" style="width: 100%; height: 285px;"></div>
<p:commandButton type="button" value="Route" onclick="PathFinder.findAndGo()"/>
<div id="route"></div>
</pm:content>
</ui:define>
</ui:composition>
The JavaScript function PathFinder.findAndGo is defined in my master.xhtml
The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
same for jQuery: $(document). ready(function() { //same as: $(function() { alert("hi 1"); }); $(window). load(function() { alert("hi 2"); });
The first approach for calling a function on the page load is the use an onload event inside the HTML <body> tag. As you know, the HTML body contains the entire content of the web page, and when all HTML body loads on the web browser, it will call the function from the JavaScript.
Use JQuery as follows:
<script>
jQuery(document).ready(function() {
PathFinder.findAndGo();
});
</script>
Update:
It has to be within <ui:define name="content">
.
There are 2 ways that work for me, when I want to execute a JS function after page load in Primefaces:
jQuery(document).ready(function () {
jQuery(document).ready(function () {
// twice in document.ready to execute after Primefaces callbacks
PathFinder.findAndGo();
});
});
<p:remoteCommand oncomplete=" PathFinder.findAndGo(); " autoRun="true"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With