0

There are several questions around similar to this and I have tried all suggestions, to no avail.

I have a text area and a button. The button is initially hidden, but when the user types anything the button is shown.

In addition to this I want to scroll the page so that the button becomes visible. Example:

$(document).ready(function () {

    $('#AddCommentEntryBox').on('keyup', function (e) {
        if ($(this).val() !== '') {
            $('#AddCommentButton').show();
            $(window).scrollTop($('#AddCommentButton').position().bottom);
            //$("html, body").animate({ scrollTop: $(document).height() }, 1000);
        } else {
            $('#AddCommentButton').hide();
        }
    });
});

http://jsfiddle.net/sJQcM/

EDIT: better example - I need to scroll a parent element, not the page:

http://jsfiddle.net/sJQcM/3/

2
  • unfortunately, you cannot scroll to a hidden element. Commented Jun 17, 2013 at 14:32
  • The button is shown before I scroll. I got it working here: jsfiddle.net/sJQcM/4. This is enough but it won't work if the button isn't the bottom element. Commented Jun 17, 2013 at 14:39

1 Answer 1

3
$(document).ready(function () {
    $('#AddCommentEntryBox').on('keyup', function (e) {
        if ($(this).val() !== '') {
            $('#AddCommentButton').show();
            $('html, body').stop().animate({scrollTop:$('#AddCommentButton').offset().top})
        } else {
            $('#AddCommentButton').hide();
        }
    });
});

FIDDLE

You may want to exclude the backspace from this.

Your example may have also worked, the reason it didn't is because .position() gives only .top or .left. Bottom is not given (you have to calculate it yourself).

You can also use .animate() with scrollTop for smooth scrolling. In addition I recommend you wait for the user to stop typing for a few seconds before scrolling, otherwise it will scroll down and the textarea will be only partially visible.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks :) Why did you change position() to offset()?
as you can see here in the console the offset() gives you the position of the element in proportion to the window, while position() gives the position of the element in it's parent (a little different although here not so much, use whichever fits you better)
Hmm it doesn't quite work in my situation. In my page the body has overflow: hidden. I have a MainSection element that I need to scroll. At a minimum I need to simply scroll the parent div to the bottom. See edit.
I marked this as the answer. The technique is correct - now I just have to work on the scroll calculations specific to my page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.