2

I'm doing a chat via websockets, that's another story, but I'm getting some undesired scrolling when I try to focus the textareas inside the chat boxes. I have this basic structure so you can click the partially visible windows (the user's name is shown in that area) and the windows become fully visible.

<div class="container"></div>
<div class="content">
    <div class="block"><textarea></textarea></div>
    <div class="block"><textarea></textarea></div>
</div>

Let's say that the container is all the other content itself, the content div is the chat windows container, and the blocks are the chat windows.

You can see it in this jsfiddle http://jsfiddle.net/Mhrvf/1/

There's no problem when I don't focus the textarea, but when I focus it the browser tries to scroll all the content to make the textarea visible, then each time I bring the chat window up, my body content scrolls a the distance between the window bottom and the textarea.

You can see the problem here http://jsfiddle.net/Cc25T/
Look at the scroll bar each time you open a "conversation"

I hacked into delaying the focus enough time so the animation is ended and the textarea is yet visible. Like this: http://jsfiddle.net/Cc25T/3/

But... is there a better way? Personally I don't like to rely on timeouts, so any suggestion is welcome :)
I know I could use jQuery animate and it's callback, but I just preffer not to, because of how expensive it is, and the way better animations support when using CSS Transitions (I know IE doesn't support it, I don't care)

kevLinK
  • 87
  • 2
  • 12

2 Answers2

1

For transitions you can use the following to detect the end of a transition via jQuery:

$('.block').click(function () {
   $(this).bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
       $(this).children('textarea').focus();
  });
    $(this).toggleClass('show');
});

jsfiddle - http://jsfiddle.net/Cc25T/4/

Moazzam Khan
  • 3,130
  • 2
  • 20
  • 35
1

Thanks to the details provided from @Moazzam Khan I managed to handle the event. It's just that the bind event could fire twice if the browser handle the transitionend simple event, so I used one. Besides that I had to validate if the block had the show class, or it would focus it always, leading to the same result.

$('.block').click(function () {
    $(this).one("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd",
    function () {
        if ($(this).hasClass('show')) $(this).children('textarea').focus();
    });
    $(this).toggleClass('show');
});

That worked pretty good, as you can see here: http://jsfiddle.net/Mhrvf/3/

kevLinK
  • 87
  • 2
  • 12