Navigate to route on button click

Viewed 25775

When I click on the following button, I would like to be redirected to the route specified in the href. However it doesn't work:

<button href="/auth"> Google+ </button>

I am not sure if it matters but I am running a node app.

How can I navigate to a route on button click?

8 Answers

Buttons were not initially designed for the purpose of redirecting to a new page. Instead, what you are looking for is the a tag. From reading the comments, however, it is clear that you would like to keep the button element and add the same functionality for redirecting without the use of JavaScript, so I will provide a couple of solutions:

With JavaScript

var button = document.getElementById('myButton');
button.onclick = function() {
  location.assign('https://stackoverflow.com/questions/52229901/navigate-to-route-on-button-click/');
}
<button id="myButton">Visit Website</button>

Without JavaScript

<form action="https://stackoverflow.com/questions/52229901/navigate-to-route-on-button-click/">
    <input type="submit" value="Visit Website"/>
</form>

You can use the following solution to navigate to the route on a button click:

<button onclick="clickFun()"> Google+ </button>
<script>
    clickFun() {
        window.location = '/auth';
    }
</script>

Buttons need an onClick handler. The href attribute is for links (anchor tags, more specifically).

<button onClick='someFunction'>Google</button>

<script>
    someFunction() {
        window.location = 'some-url';
    }
</script>

The best way to rout some different page: we have native javascript method location.asign('here your link'); For example

var btn = document.getElementById('btn');
btn.onclick = function() {
location.assign('https://stackoverflow.com/questions/52229901/navigate-to-route-on-button-click');
}
<button id="btn">
  click 
</button>

You can use an a element instead:

<a href="/auth"> Google+ </a>

Its very simple you can't use link inside the button tag but you can add tag outside the button tag

for example

<a href='www.google.com'><button>Click me</button></a>

rest depends on your css skills

You can put the link inside the button and give the link href property , style the href class as per need

    <button class="button is-success" onclick={submit}>
      <a href="/auth" class="href">
        Save changes and Submit
      </a>
    </button>

You can nest your button inside the anchor tag

<a href="/auth">
  <button> Google+ </button>
</a>
Related