I want to use jQuery to go to an anchor with the use of a textbox, for example, I want to use this form:
<form id="gotoanchorform">
<input id="gotoanchorinput" type="text" />
<input type="submit" value="Go to anchor" />
</form>
In this form I would type the name of the anchor and when I click the "Go to anchor" button or press the enter key I want the page to scroll down to that anchor:
<a name="targetAnchor" id="targetAnchor">Target</a>
How would get this to work with jQuery?
var anchor = $("#gotoanchorinput").val();
var position = $("#"+anchor).offset();
window.scrollTo(position.left, position.top);
This piece of code make your page scroll to the anchor written in #gotoanchorinput
.
try something like this:
$(function() {
$('form#gotoanchorform').submit(function(e) {
e.preventDefault();
var desired = $('#gotoanchorinput').val();
window.location.href = window.location.href + '#' + desired;
// or
$('html, body').animate({'scrollTop', $('a[name*="' + desired +'"').offset().top + 'px'}, 900);
return false;
});
});
so if you would type "foo" and click submit, the page would scroll to an which name attribute contains "foo"
HTML part:
<form id="myForm" data-anchor="#myAnchor">
<input type="text" />
<input type="submit" value="Go to anchor" />
</form>
NB: data-x attribute is valid HTML.
JS part:
$(document).ready(function() {
$('#myForm').submit(function(e){
$(location).attr('href', $(this).attr('data-anchor'));
return false;
});
});
Simply do:
var url = $('#gotoanchorinput').val();
$(location).attr('href',url);