Ask coding questions

← Back to all posts
How to make buttons act as... well, buttons!
aflacc (9)

If you run the Repl i attached, clicking the buttons does not work and only clicking the text on the button does. I did this because the <a> tag allows href and the <button> tag does not. Basically I just did this:

<button><a>Link here!</a></button>
Answered by MatReiner (123) [earned 5 cycles]
View Answer
MatReiner (123)
<button onclick="location.href=`url_here`">Link here!</button>
Vandesm14 (2645)

@MatReiner and @aflacc It's not a good idea to use a button as a link. I suggest checking out MrEconomical's answer. Using links is better since it's good practice and keeps accessibility.

MatReiner (123)


<a style="display: inline-block;width: 100%;text-align: center;position: relative;top: 50%;transform: translateY(-50%)">
MrEconomical (2290)

that's because the <a> tag only redirects if somebody clicks on it. You can just style the <a> tag itself and not worry about the button (width, height, etc.)

Highwayman (1443)

You could add an event listener to the button that sends the client to a new page using js.
To add an event listener in html, do

onclick="js_stuff()" <!-- this causes the js_stuff() function to run on the "click" event. -->
MatReiner (123)

@Highwayman just location.href = "url"

Highwayman (1443)

@MatReiner huh. Really? That’s surprisingly simple! I would think it just changes the link in the search bar, but doesn’t necessarily make the request. Huh. I was thinking along the lines of"link","_self"); or however it goes :P

Edit: also sick profile pic :D

MatReiner (123)

@Highwayman For a second, I thought you said you were sick of it!