I have a button as an image...
<img src="button.png" />
I need some javascript in an onclick where when click it will navigate to a local anchor. For example:
<img src="button.png" onclick="navigateTo #page10" />
How can I do this?
Update: This is the code I'm using:
onclick="document.location=#goToPage';return false;"
Using onclick Event: The onclick event attribute works when the user click on the button. When mouse clicked on the button then the button acts like a link and redirect page into the given location. Using button tag inside <a> tag: This method create a button inside anchor tag.
If you want to call a function when the onclick event happens, you'll just want the function name plus the parameters. Then if your parameters are a variable (which they look like they are), then you won't want quotes around them.
We can bind a JavaScript function to a div using the onclick event handler in the HTML or attaching the event handler in JavaScript. Let us refer to the following code in which we attach the event handler to a div element. The div element does not accept any click events by default.
JavaScript String anchor() It may cease to work in your browser at any time. The anchor method returns a string embedded in an <a> tag: <a name="anchorname">string</a>
The solution presented in the accepted answer has the important issue that it can only be used 1 time. Each consecutive click appends #goToPage
to location and the window won't navigate to the anchor.
A solution is to remove the anchor part before appending a new anchor:
function goToAnchor(anchor) {
var loc = document.location.toString().split('#')[0];
document.location = loc + '#' + anchor;
return false;
}
Usage example:
<a href="#anchor" onclick="goToAnchor('anchor')">Anchor</a>
NOTE: The anchor needs to be enclosed in quotes, without the hash prefix.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With