0

I have an input on my page that I would like to use for search. I would like the page to jump to the location of the user's input value.

HTML:

<input name="searchInput" type="text" id="searchInputOne" class="searchInput" />
<input type="button" id="submitButton" value="Search" />

JS:

var input = document.getElementById("searchInputOne");
var submit = document.getElementById("submitButton");

function search() {
     window.location = window.location.href + "/" + input.value;
}

submit.onclick = search;

This makes sense in my head, but it doesn't work in practice. I'm sure my search function is wrong. How can I make it right? I would like to stay with pure JS.

Claire
  • 3,146
  • 6
  • 22
  • 37
  • Why doesn't it work? Can you add a snippet? – Jorjon May 22 '18 at 00:36
  • I tried to create a fiddle but it would not let me save. Upon further research I think I've discovered fiddle does not allow `window.location` changes. – Claire May 22 '18 at 00:37
  • similar problem to this article https://stackoverflow.com/questions/13735912/anchor-jumping-by-using-javascript ? – Jack Le May 22 '18 at 00:39
  • @JackLe Not at all. That article is discussing anchor links. This is user input. No anchor links involved. – Claire May 22 '18 at 00:41
  • @ATomCalledStu you need anchor links to navigate within the same page. Or instead of "jumping" to matching sections, why don't you just hide all of the search results except the matching ones – Jack Le May 22 '18 at 00:46
  • not sure why you would let a user type anything they want then try to jump there. You will end up with a bunch of 404 errors. – Bindrid May 22 '18 at 00:56
  • inside the search function, you can try replace 'window.location' with 'window.location.href'. – Perry2008084 May 22 '18 at 01:36
  • @JackLe No you do not. You don’t understand what I’m trying to do I guess – Claire May 22 '18 at 02:34

1 Answers1

0

I would like the page to jump to the location of the user's input value

Select the element by its identifier and then use the window.scrollTo() method to go to the element's top position determined by its offsetTop's value.

var elem = document.querySelector("#" + typedValue);
window.scrollTo(0, elem.offsetTop);

I assume you know how to get the typed value.

Alexis88
  • 297
  • 1
  • 11