Trigger custom AJAX function onevent with JSF

In this tutorial we will trigger a custom AJAX function onevent with JSF. You can bind a javascript function when an AJAX event occurs in different ways. You can either bind a javascript function using the onevent attribute of the <f:ajax> element. Or you can globally bind an event listener using the jsf.ajax.addOnEvent(methodName) function.

Processing Managed Bean

In the example we’ll display a loading gif to indicate the process is executing. We use the wait() method to execute this method for 3 seconds.

package com.memorynotfound;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

public class ProcessingBean {

    public void processing(){
            try {
            } catch (InterruptedException e1) {
                // waiting interrupted


Execute Custom JavaScript on JSF AJAX onevent

We can bind a custom JavaScript function using either the onevent attribute of the <f:ajax> element. Or by globally defining an event listener using the jsf.ajax.addOnEvent(methodName) function. Both methods require the jsf.js script.

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html xmlns=""
    <h:outputScript library="js" name="custom-script.js" target="body"/>
    <h:outputScript library="javax.faces" name="jsf.js" target="body"/>
    <script type="text/javascript">

    <h2>JSF 2: onevent ajax</h2>

    <h:form id="user-form">
        <h:panelGrid columns="1">

            <img src="resources/img/ajax-loader.gif" id="spinner" style="display: none"/>

            <h:commandButton value="Submit" actionListener="#{processingBean.processing}">
                <f:ajax render="@form" onevent="onStatusChange" />



Info: In order for the javascript selectors to work we have to change our default char separator.

<!-- change default separator for javascript and css selectors -->

Custom JavaScript Loader

function onStatusChange(data) {
    var spinner = document.getElementById("spinner");
    var status = data.status;
    if (status === "begin") { = "inline";
    } else { = "none";


URL: localhost:8081/jsf-ajax-onevent

jsf ajax onevent

When the button is pressed.

jsf ajax onevent



Download it ! – jsf ajax onevent

You may also like...