0

I have been working on a little project for a day or two. The code is the following.

<!DOCTYPE html>
<html>
<head>
<script>

function search() 
{
document.getElementById("text1").value


window.location.hash = "myVariable";
}
</script>

</head>
</body>
<form name="myform">
<input type="text" name="text1" value="">
<input type="button" value="Search" onclick="search()">
</form>


<div style="height: 4000px"></div>
<span id='yeah'>I have successfully jumped.</span>
<div style="height: 4000px"></div>

</body>
</html>

Now you may be wondering what am I trying to accomplish with this code? Well, I want to be to enter a value in the text box and then it will jump me to the section (the section is the value in the text box). It is sort of like a search engine, but it is not.

For example the section is yeah. When a user enters yeah in the text box it is supposed to jump them to the yeah section. Instead nothing happens. And despite looking all over the Internet I have not found an answer that satisfies my needs, so I would kindly ask that you please explain to me what my problem is and possibly give me a solution to my problem.

I am using the Mozilla Firefox web browser (if that information is necessary).

2 Answers 2

1

Try this:

function search() 
{
  var elID= document.getElementById("text1").value;
  var el = document.getElementById(elID);

  el.scrollIntoView(true);
}

The Element.scrollIntoView() method scrolls the element into view

Online Demo

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

Comments

0

Dalorzo's should work, but jQuery could be the better option than raw javascript if you plan to add more than just this function.

Here's a fiddle of what you're trying to do.

$("#button1").click(function() {
    var t = $("#text1").val();

    alert(t);

    $('html, body').animate({
        scrollTop: $("#"+t).offset().top
    }, 2000);
});

3 Comments

I'd suggest the other way around -- for simple tasks like this raw JavaScript is a much preferred solution and will induce a lower overhead.
True, it's a lot heavier. If this is the only javascript needed then yes, raw is logical. I'm making the assumption that this function will be expanded upon.
That is all I want to do with that function. However, jQuery seems interesting and I think I will read more into it. So I guess you did solve my problem, in a way.

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.