2

Here is my HTML structure:

<body>
    <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
    <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />

    <div class='error'>error message</div>

    <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
    <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
</body>

Here is my CSS code:

.error{
    display: none;
}

Here is my Jquery code:

// detect pressing enter on keyboard
$(document).keypress(function(e) {
    if(e.which == 13) {
        $('.error').show();
    }
});

What the above code does: when user press <enter>, <div> will be shown.

What I want: when <div> shown, if it was in the screen then nothing, but if it was not in the screen, page scrolls and stops where <div> is in the screen, how can I do that?

It should be noted that I don't want this: position: fixed;

Shafizadeh
  • 9,960
  • 12
  • 52
  • 89

2 Answers2

3

created fiddle

Modified your JS a bit, plz have a look

$(document).keypress(function(e) {
    if(e.which == 13) {
        $('.error').show();
         $('.error')[0].scrollIntoView(true);
    }

});
Nilesh Mahajan
  • 3,506
  • 21
  • 34
  • Can I set `20px` space between top and div ? actually I have a fixed header in my website, and in this case, div goes under the header. – Shafizadeh Sep 24 '15 at 09:37
  • @Sajad Yes you can, check my updated fiddle. I added padding to the error div. now it will leave 20px top padding – Nilesh Mahajan Sep 24 '15 at 09:44
2

Try doing it like this.

<div id='focus' class='error'>error message</div>

$(document).keypress(function(e) {
    if(e.which == 13) {
        $('.error').show();
        document.getElementById('focus').scrollIntoview();
    }
});
Vibhesh Kaul
  • 2,593
  • 1
  • 21
  • 38