Marcos
Marcos

Reputation: 1265

Render PrimeFaces <p:focus> component only if the browser window has a certain size

Is there a way to render the PrimeFaces <p:focus> component (or let it do its job) only when the browser window has a certain size? To do this I understand that maybe I have to have access the browser window size in server code and use the component rendered attribute to access this code.

In client code, I get the window width with code like this: $(window).width() > 480.

The reason for this is that I don't want to focus the first component in mobile devices, which most of the time have small screens.

Today I'm doing this with the client code below, but I'd like to use the <p:focus> component for the task, as it also has the benefit to focus the first invalid component when validation fails.

$(
    function()
    {
        if (bigWindow())
        {
            focusFirstInput();
        }
    }
)

function bigWindow()
{
    return $(window).width() > 480;
}

function focusFirstInput()
{
    $("#form input:text, #form input[type=number], #form input[type=password], #form textarea").
        first().focus();
}

Upvotes: 2

Views: 134

Answers (1)

Marcos
Marcos

Reputation: 1265

I've found a way using the <p:focus> component:

$(
    function()
    {
        let primeFacesOriginalFocusFunction = PrimeFaces.focus;
        PrimeFaces.focus =
            function(id, context)
            {
                if (!isMobile())
                {
                    primeFacesOriginalFocusFunction(id, context);
                }
            }
    }
)

function isMobile()
{
    return ...
}

Upvotes: 3

Related Questions