This is an old question but at this time has been viewed 10,354 times. I want to share the way i resolve 'add a css style property dynamically' in primefaces 6.2
In my layout i have a header that i need change dyamically the image every 10|20 secs.
<h:panelGrid id="cabecera" columns="2" cellpadding="1" columnClasses="..."
style="width:100%; background-size: cover; background-position: center; background-image: url('#{request.contextPath}/resources/images/header/Vignette/#{userSelected.headerFile}');">
<h:form id="...." >
I have a list with the names of all the images that i can use and userSelected.headerFile choose one randomly.
Three similar options:
1.- At first i Use p:poll directly to update the panelGrid id 'cabecera':
<p:poll interval="10" update="@([id$=cabecera])" autoStart="true"/>
Of course that works, on every update the background image change. That could be enough in some cases where the update and page blink don´t be problem.
2.- Using a little of JavaScript, a bean method in the listener of p:poll.
Declare a js function to change the background property (or any other):
<script>
function headerBackground(urlBG) {
var laUrl = (urlBG);
document.getElementById('cabecera').style.backgroundImage = laUrl;
}
</script>
In my Bean userSelected i declared a method to call the javascript function via RequestContext.getCurrentInstance().execute(...). I decided received the url only and add the rest of values in the function:
public void callJSheaderBackground(String url) {
String jsFunc="headerBackground(\"".concat(url.trim()).concat("\")");
try{
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute(jsFunc);
}catch(Exception ex){
...
}
}
Finally the p:poll
<p:poll interval="20" listener="#{userSelected.callJSheaderBackground('url(\''.concat(request.contextPath).concat('/resources/images/header/Vignette/').concat(userSelected.headerFile).concat('\')'))}" autoStart="true"/>
3.- Calling directly a JS function
My JS function, reciving the contextPath and the image file name as parameters:
function setVignetteAsBackground(contextPath,vignetteName) {
var laUrl = "url('" + (contextPath)+'/resources/images/header/Vignette/'+(vignetteName)+"')";
document.getElementById('cabecera').style.backgroundImage = laUrl;
}
Then directly calling from p:poll on the onstart|oncomplete event:
<p:poll interval="20" onstart="setVignetteAsBackground('#{request.contextPath}','#{userSelected.headerFile}')" autoStart="true"/>
Hopefully be useful for somebody.