Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll p:messages into view when it is updated and (error) messages are present

I am working with PrimeFaces messages, I want my whole page to scroll to top when p:messages is rendered.

like image 808
Ami Avatar asked Apr 02 '14 07:04

Ami


3 Answers

Assign an ID to your p:message component

<p:messages autoUpdate="true" id="myMessage" />

Then, in your backing bean call RequestContext.scrollTo method:

  • in PrimeFaces >= 6.0:

    PrimeFaces.current().scrollTo("myMessage")
    
  • in Primefaces < 6.0:

    RequestContext context = RequestContext.getCurrentInstance();
    context.scrollTo("myMessage");
    

    which is deprecated in PrimeFaces 6.0

like image 131
Jorge Marmolejo Avatar answered Nov 01 '22 11:11

Jorge Marmolejo


Deprecated with PrimeFaces < 6.2

In you backing bean (that one which produces the messages), you should know when you render a p:message. If so simply execute this:

RequestContext.getCurrentInstance().execute("window.scrollTo(0,0);");

Update:

With the newer PrimeFaces versions (>= 6.2), the approach to execute Javascript on the client side is (by using x and y coordinates):

PrimeFaces instance = PrimeFaces.current();
instance.execute("window.scrollTo(0,0);");

To scroll to an element use the element's clientId:

PrimeFaces instance = PrimeFaces.current();
instance.scrollTo("myElementsClientId");

Find more information here:

  • http://de.selfhtml.org/javascript/objekte/window.htm#scroll_to
  • examples with jQuery for smooth scrolling as well: Scroll to the top of the page using JavaScript/jQuery?
like image 6
Manuel Avatar answered Nov 01 '22 13:11

Manuel


Lets say that your button is causing the messages to appear.

XHTML

<p:commandButton value="Save" 
                 oncomplete="scrollToFirstMessage()" />

javascript

//javascript function which scroll to the first message in page   
function scrollToFirstMessage() {
     try {
        PrimeFaces.scrollTo($('.ui-message :first-child').eq(0).parent().attr('id'));
     } catch(err) {
       //No Message was found!
     }
  }

Hope this helps.

like image 1
Hatem Alimam Avatar answered Nov 01 '22 13:11

Hatem Alimam