I am working with PrimeFaces messages, I want my whole page to scroll to top when p:messages
is rendered.
There are valid answers already that show how to scroll to the p:messages
component, but they all require you to execute code in a backing bean. This requires you to do / call the same in each action. None show how to scroll to the messages component when it is rendered (updated).
You can implement a phase listener and check messages are present and if the messages component's clientId
is present in the PartialViewContext renderIds
:
These client identifiers are used to identify components that will be processed during the render phase of the request processing lifecycle.
Your listener can look something like this:
public class MessagesUpdateListener implements PhaseListener {
private final String MESSAGES_ID = "yourMessagesClientId";
@Override
public void afterPhase(PhaseEvent event) {
// Empty
}
@Override
public void beforePhase(PhaseEvent event) {
FacesContext fc = FacesContext.getCurrentInstance();
if (!fc.getMessageList().isEmpty() &&
fc.getPartialViewContext().getRenderIds().contains(MESSAGES_ID)) {
RequestContext.getCurrentInstance().scrollTo(MESSAGES_ID);
}
}
@Override
public PhaseId getPhaseId() {
return PhaseId.RENDER_RESPONSE;
}
}
Make sure to register it in your faces-config.xml
:
your.MessagesUpdateListener
Tested with XHTML:
this
is
a
long
page
this
is
a
long
page
this
is
a
long
page
this
is
a
long
page
this
is
a
long
page
this
is
a
long
page
this
is
a
long
page
this
is
a
long
page
this
is
a
long
page
this
is
a
long
page
this
is
a
long
page
this
is
a
long
page
this
is
a
long
page
this
is
a
long
page
To check for global messages, use:
fc.getMessageList(null).isEmpty()
See also: