I have designed a long form around two pages. After the user submits the form, I need to force him/her to see the top of the form if the form contains any errors.
I have an error holder on top of the form.
My question is how to make the browser scrolls to the error holder so that the user can easily see it?
Thank you
/////////////////////////////////////////// follow Peter’s comments
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>jQuery</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
// This is a functions that scrolls to the element with id id
function goToByScroll(id)
{
// Scroll
$('html,body').animate({
scrollTop: $(id).offset().top}, 'slow');
};
$(document).ready( function() {
debugger;
$('#clearhere').click(function() {
goToByScroll('topbar2');
});
});
</script>
</head>
<body>
<div id="topbar2">Hello world</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<button type="button" id="clearhere" name="clearhere">Click Me!</button>
</body>
</html>
///////////////////////////////////////////
To scroll to the top an element simply make use of the jQuery .animate() and .offset() functions. For example to scroll to the top of an element with a particular selector (such as an id) passed in as an argument, use this:
For example, if you have only one form on the page, you can use:
goToByScroll("form");. If you want to scroll to an element with a particular id usegoToByScroll("#myId");… etc.If you want to adjust the scroll time to an exact number of milliseconds, just replace
'slow'with the number of millisecond, for example1000(no quotes) for a scroll of 1 second.Just trigger the above function when you want to scroll to the top of your form.
Here’s a live jsFiddle example (as a 5 line jQuery plugin)