Utilizing JavaScript to navigate to a specific section within a webpage upon clicking an inline element

Alternative 2: Navigate to or scroll to a specific div id without modifying the URL. However, while attempting this approach with Nextjs and desiring a seamless transition to a lower element, I encountered an issue. This issue pertains to Nextjs and Typescript.

Question:

I have a button as an image…


I require the implementation of javascript within an onclick event, which, upon clicking, will redirect to a local anchor. An instance of this would be:


How can I do this?

Update: This is the code I’m using:

onclick="document.location=#goToPage';return false;"


Solution 1:

The solution provided in the accepted answer has a significant drawback – it can only be utilized once. Subsequent clicks will add

#goToPage

to the URL, but the window will not navigate to the anchor.

An alternative is to eliminate the anchor portion prior to adding a new anchor.

function goToAnchor(anchor) {
  var loc = document.location.toString().split('#')[0];
  document.location = loc + '#' + anchor;
  return false;
}

Usage example:

Anchor

Please note that the anchor should be enclosed in quotation marks, and the hash prefix should be omitted.


Solution 2:


The suggested value for

onClick

appears appropriate.

onclick="document.location+='#goToPage';return false;" 


Solution 3:


Enclose it with an anchor tag without the requirement of JavaScript.



Solution 4:

Experiment with the forward slash (/) to designate the root or a specific folder, enabling its repeated usage.

onclick="document.location='/#goToPage';return false;" 
onclick="document.location='/folder/#goToPage';return false;" 

Frequently Asked Questions