I dont know how to make the html page to scroll to particular string being part of url.
For eg: if suppose user gives
The html page contains lot of utc time values, based on user given value of utc in url, the page should scroll to that utc which user has given in url.
Can you please suggest on how to do this in html, javascript etc?
3
Answers
Try the below code:
Replace utc_1234567890 in the code with your div element id to scroll to and replace 1234567890 with the respective utc value in the URL
Use
URL searchParams
andscrollIntoView()
method.Working example on codepen.
In the example below, there will be scrolling to the block if the url contains
?utc=123
:Basically, your browser would automatically jump to the anchor link as soon as it is contained in the url. i.e. ?utc=7 automatically jumps to the place in the DOM where the anchor is set when you call up the link. So to the place
<div id="7">Hello World</div>
. If you manipulate the url in a spa application, it is of course possible that the browser does not immediately jump to the location. here you can trigger this via the js location api or you simply trigger a page reload 😉 (the easiest way).Here is a short example on the topic of anchors in general.