viernes, 24 de enero de 2014

Mysterious scroll

Today I'd like to speak about a problem that we had with CSSModal and Autofocus.

What do we use in our application?
 - Rails
 - For modal windows CSS Modal. For example, we have at the top of the index page a link for login. When we click this link, a modal with a form for the login is opened.

 The problem showed up when we used the autofocus attribute in our forms. The result was that when we opened the index page, it was scrolled to the middle of the page, without clicking the login link.

 I didn't know that the autofocus could cause this behaviour, so I created a JS to test what it was happening:

console.log(document.activeElement);
console.log($(window));
console.log('$(window).scrollTop() ' + $(window).scrollTop());
console.log('$(window).height() '+ $(window).height());
console.log('$(document).height() ' + $(document).height());
console.log('window.pageYOffset ' + window.pageYOffset);
console.log('document.body.scrollTop ' + document.body.scrollTop);

I saw that the activeElement was always the first field of the login form. How could it be? I didn't click the login link.

Thilo, told me that perhaps the autofocus of the login form was changing the pageYOffset. He removed the link and tested that the page worked properly.

So, I removed the autofocus in the modal forms and the pages worked.

But I needed the focus in the first field of each form!!!

How did we resolve? With JS.

In the input or text fields of our forms with the needed autofocus, we used a html class called "should_have_focus"

Then, in a js file:

$(document).on('cssmodal:show', function () { 
     $('.is-active') 
          .find('input.should_have_focus, textarea.should_have_focus')
          .focus();
});

When the modal is active, the focus is transferred to the input or textarea field with the html class "should_have_focus"

And that's all!!

No hay comentarios:

Publicar un comentario