1

I'm new in HTML and I would like some help, I would like to create an HTML button that acts like a link.

So, when you click the button, it redirects to a page locally stored in the same file, which is named "page 2 html",

I have a code line:

<button type="submit">connect</button>

I would like to add a "window.onclick" function to this button which redirect to "page 2 html" and what will be the javascript function that goes with it?

Thanks.

Deepak Rai
  • 2,163
  • 3
  • 21
  • 36
SparkhaoS
  • 11
  • 1
  • 3
  • 2
    Don't. If you want something that acts like a link: Use a link. The browser will give it all the normal behaviours of a link (like being able to right click and copy the URL or open in a new tab or being announced as a link by a screen reader or search engines like Google being able to find the link). If you don't like the way links look: Apply CSS. – Quentin Feb 23 '21 at 21:41
  • Does this answer your question? [How do I create an HTML button that acts like a link?](https://stackoverflow.com/questions/2906582/how-do-i-create-an-html-button-that-acts-like-a-link) – computercarguy Dec 21 '22 at 16:49

2 Answers2

3

There are a number of ways to do this, If you are stuck to a submit button, you would have to tie it to a form, then make the form's action attribute the link:

<form>
  <button type="submit" formaction="https://placekitten.com/">Click Me</button>
</form>

or you could do it as a regular button:

var gimmeCats = () => {
  window.location.href = "https://placekitten.com/";
}
<button id="catBtn" onclick="gimmeCats()">Click Me!</button>

Or, if you aren't opposed to bootstrap, there is this:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

<a href="https://placekitten.com" class="btn btn-primary">Click Me!!!!!!!!!</a>
Jacrys
  • 692
  • 1
  • 7
  • 20
1

Using window.onclick will not do it because you are telling your browser that when you click anywhere in the window it will execute it. So you can use location.replace('') like this:

   <input type="submit" onclick="location.replace('page2.html')"/>

Or using a regular button:

<button onclick="location.replace('page2.html')">Page 2</button>
Or by using a function:
 <script>
  function redirect() {
   location.replace('page2.html');
 }
 </script>
  <button onclick="redirect()">Redirect</button>
You could also just use a normal <a> tag:
<a href="page2.html"><button>Redirect</button></a>
YT_Xaos
  • 335
  • 4
  • 19