I honestly love jQuery javascript library, and absolutely am disappointed with JavaServer Faces (JSF).
jQuery is a neat library, that eases the javascript development, by enabling CSS (and other) search capabilities.
For instance if you want to change the background color to red for all items with the class “myClass” you just have to query $(".myClass").css("background", "red");.
I’m not going to go further on jQuery since there are a lot of tutorials out there. My problem was when I was trying to integrate jQuery with a JSF application. JSF as the neat “feature” of generating id’s for all our rendered components based on the view (or subview) which the component is on.
So if I have a <h:inputButton id="button1"/> the generated id will be view:button1. Which causes a main problem when you want to apply CSS styles to this element. You can’t simply add style to #view:button1 because it’s not CSS valid. And for making it worse, you can’t query using jQuery for this element to… so you see where I’m getting at.
The solution I found was to use the j4j Tag Library idProxy to generate a chosen id for the components we want to manipulate via jQuery. The j4j idProxy generates an invisible span (I believe it’s label or a span element) with the id we wanted, and a title of the JSF generated id for our component.
So for our later inputButton we would replace with <h:inputButton id="button1"><j4j:idProxy id="myButton"/></h:inputButton> and get a <span id="myButton" value="view:button1"></span> right beside of our rendered inputButton component.
But still, this is not enough because if I want to manipulate via jQuery the input button we still have no way to access our component! So we need a javascript function, let’s name it jsf() which receive a <j4j:idProxy> generated id and returns our JSF component jQuery object!
function jsf(id){
//Finds the j4j Element and retrieves the ID of the target component which is stored on the title attribute
realId = document.getElementById(id).title;
//Finds the JSF component
var element = document.getElementById(realId);
//Returns an jQuery element based on the DOM element of our target component
return $(element);
}
And voila! Now all we have to do to use jQuery on a JSF web application is to put the j4j:idProxy on every JSF component we want to manipulate and use the chosen id with the jsf() javascript function.