Creé un cuadro de búsqueda, cuando el usuario busque en él se centrará en lo que busca el usuario. Si busco Acerca de, me enfocaré en el título "Acerca de", luego me desplazo hacia abajo o hacia arriba y busco nuevamente Acerca de que no se enfocó en nada.
function Focus() { var search = document.getElementById("search-box").value; if (search.toLowerCase() == "about") { window.location.hash = '#about'; document.getElementById("search-box").value = ""; console.log("about") } else if (search.toLowerCase() == "skills") { window.location.hash = '#skill'; document.getElementById("search-box").value = ""; console.log("skills") } else if (search == "") { alert("Search Field is empty. Type anything"); } else { alert("Not Found"); document.getElementById("search-box").value = ""; } } <input type="search" id="search-box" placeholder="Search"> <button type="submit" id="searchbar" onclick="Focus()">Search</button> <h1 id="about">About</h1> <h1 id="skill">Skills</h1> <!-- There are so many things under this titles. -->Borre el hash antes de asignar un nuevo hash. window.location.hash = '';
if (search.toLowerCase() == "about") { window.location.hash = ''; window.location.hash = '#about'; document.getElementById("search-box").value = ""; } else if(search.toLowerCase() == "skills") { window.location.hash = ''; window.location.hash = '#skill'; document.getElementById("search-box").value = ""; } else if(search==""){ alert("Search Field is empty. Type anything"); } else{ alert("Not Found"); document.getElementById("search-box").value = ""; }El problema es que el hash (#about) no cambia cuando buscas el mismo hash dos veces. El navegador solo se desplazará si el hash cambia.
Creo que la mejor manera es buscar el elemento cuando hace clic en el botón de búsqueda y obtiene el desplazamiento del elemento y luego se desplaza a esa posición:
Obtenga el desplazamiento del elemento:
element.getBoundingClientRect().top + document.documentElement.scrollTopDesplácese a Posición
window.scroll(x, y)Como @Balaji Sivasakthi ya respondió, me gustaría señalar que repite mucho código.
search como una variable, puede usar esa variable para getElementById .element a continuación), y puede verificar si existe.message y coloque una alerta fuera de las declaraciones if. Si el mensaje tiene algún valor aparte de "", active la alerta. function Focus() { var searchBox = document.getElementById("search-box") var search = searchBox.value.toLowerCase(); // 2 var element = document.getElementById(search); // 2 & 3 var message = ""; // 4 window.location.hash = '#'; if (element) { // 3 -- checks if you found any elements with id #{search} window.location.hash += search; // adds element id to hash console.log({search}); } else if (search) { // 2 & 4 -- anything else than "" is true message = "Not Found"; } else { message = "Search Field is empty. Type anything" } searchBox.value = ""; // 1 if (message) { alert(message) } // 4 -- anything else than "" is true } <input type="search" id="search-box" placeholder="Search"> <button type="submit" id="searchbar" onclick="Focus()">Search</button> <h1 id="about">About</h1> <h1 id="skills">Skills</h1> <!-- There are so many things under this titles. -->