Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript inline onclick goto local anchor

Tags:

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;"
like image 559
Satch3000 Avatar asked Aug 05 '12 09:08

Satch3000


People also ask

Can I use onclick in anchor tag?

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.

How do you pass two values on Onclick?

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.

Can Onclick be used with Div?

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.

What is anchor in JavaScript?

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>


1 Answers

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.

like image 98
Tivie Avatar answered Oct 02 '22 15:10

Tivie