Как кнопке дать ссылку в html
Перейти к содержимому

Как кнопке дать ссылку в html

  • автор:

Как создать HTML кнопку, которая действует как ссылка

Есть много способов создания HTML кнопки, которая действует как ссылка, т.е., когда вы нажимаете на эту кнопку, она перенаправляется на указанный URL-адрес.

Вы можете выбрать один из следующих методов добавления ссылки на HTML кнопку.

Добавьте строчный onclick event

  1. к HTML <button> тегу внутри элемента HTML <form>.

Пример

  1. к <input> тегу внутри элемента HTML <form>.

Пример

Используйте атрибут action или formaction внутри элемента <form>.

  1. атрибут action

Пример

Для того, чтобы открыть ссылку в новой вкладке, добавьте атрибут target=»_blank» .

How to Create an HTML Button that Acts Like a Link

W3docs

S ometimes we need to create an HTML button, that acts like a link (i.e., clicking on it the user is redirected to the specified URL).

There are some methods, we are going to present 3 of them. Choose one of the following methods to add a link to an HTML button.

All right. Let’s go!

1. Add inline onclick event

a) To HTML <button> tag within HTML <form> element.

Example

It might not work if the button is inside a <form> tag.

b) To <input> tag within HTML <form> element.

Example

The links won’t work when JavaScript is disabled, and search engines may ignore such kind of links.

2. Use action or formaction attributes within <form> element

a) Action attribute

To open the link in a new tab add attribute target=”_blank”.

As there is no form and no data is submitted, this may be semantically incorrect. However, this markup is valid.

b) HTML5 formaction attribute.

Example

The formaction attribute is only used for buttons with type=”submit”. As this attribute is HTML5-specific, support in old browsers might be poor.

3. Add a link styled as an HTML button (using CSS)

Example

As complex styling is required, this may not work on specific browsers.

HTML Button Link Code Examples – How to Make HTML Hyperlinks Using the HREF Attribute on Tags

HTML Button Link Code Examples – How to Make HTML Hyperlinks Using the HREF Attribute on Tags

In this article, we are going to explore three different ways you can make an HTML button act like a link.

These are the methods we’ll go over:

  1. Styling a link to look like a button
  2. Using the action and formaction attributes in a form
  3. Using the JavaScript onclick event

But first, let’s take a look at the wrong approach.

Why doesn’t this approach with the a element work?

The code snippet below leads to the freeCodeCamp website when it is clicked.

However, this is not valid HTML.

This is considered bad practice because it makes it unclear as to the user’s intent.

Links are supposed to navigate the user to another part of the webpage or an external site. And buttons are supposed to perform a specific action like submitting a form.

When you nest one inside the other, it makes it confusing as to what action you want performed. That is why it is best to not nest a button inside an anchor tag.

How to style a link to look like a button with CSS

This first approach does not use the button at all. We can style an anchor tag to look like a button using CSS.

This is the default HTML styling for an anchor tag.

blue-anchor-tag

We can add a class to the anchor tag and then use that class selector to style the element.

If you wanted the link to open up a new page, you can add the target=»_blank» attribute like this:

Then, we can add a background color and change the font color like this:

background-and-white-text

The next step would be to add some padding around the text:

adding-padding-1

Lastly, we can use the text-decoration property to remove the underline from the text:

removing-underline

Now we have an anchor tag that looks like a button.

We can also make this «button» be a little more interactive by changing the background color depending on the state of the link.

We could get more intricate with the design, but this is just to show you the basics of styling a link like a button.

You could also choose to use a CSS library like Bootstrap.

bootstrap-styles

If your project already includes Bootstrap, then you can use the built-in button styles. But I would not import Bootstrap just to style one link.

What are the issues with this approach?

There is some debate whether it is good practice to style links as buttons. Some will argue that links should always look like links and buttons should look like buttons.

In the web book titled Resilient Web Design, Jeremy Keith states that

Why did I bother to bring up this debate?

My goal is not to make you choose one side of the debate over another. I just want you to be aware of this ongoing discussion.

How to use the action and formaction attributes to make a button in a form

How to use the action attribute

Another alternative would be to nest the button inside a form and use the action attribute.

This would be the default button style.

We could use the same styles as earlier, but we would have to add the cursor pointer and set the border to none, like this:

removing-underline-1

How to use the formaction attribute

Similar to the previous approach, we can create a form and use the formaction attribute.

You can only use the formaction attribute with inputs and buttons that have type=»image» or type=»submit» .

Is this semantically correct?

While this appears to be a working solution, there is a question if this is semantically correct.

We are using the form tags but this does not function like a real form. The purpose of a form is to collect and submit user data.

But we are using the submit button to navigate the user to another page.

When it comes to semantics, this is a not a good way to use the form tags.

Side effects for using the action and formaction attributes

When you click on the button, something interesting happens with the URL. The URL now has a question mark at the end of it.

question-mark-at-end

The reason for this change is because the form is using the GET method. You could switch to the POST method, but there might be cases where that is not ideal either.

While this approach is valid HTML, it does come with this unintended side effect.

How to use the JavaScript onclick event to make a button

In the previous approaches, we have looked at HTML and CSS solutions. But we can also use JavaScript to achieve the same result.

The location.href represents the location of a specific URL. In this case, Window.location.href will return https://www.freecodecamp.org/.

Drawbacks to this approach

While this solution does work, there are some potential issues to consider.

If the user has decided to disable JavaScript in their browser, then clearly this solution would not work. Unfortunately, that could lead to a poor user experience.

Conclusion

The goal of this article was to show you three different ways you can make buttons act like links.

The first approach was to design a link to look like a button. We also looked into the debate whether it is a good idea to change the appearance of links to look like another element.

The second approach used the form and formaction attributes. But we also learned that this approach has some side effects with the URL and is not semantically correct.

The third approach used the JavaScript onclick event and the Window.location.href. But we also learned that this approach might not work if the user decides to disable JavaScript in their browser.

As a developer, it is really important to look at the pros and cons of a particular approach before incorporating it into your project.

Every developer has a
tab open to
Stack Overflow

A public platform building the definitive collection of coding questions & answers

A community-based space to find and contribute answers to technical challenges, and one of the most popular websites in the world.

A private collaboration & knowledge sharing SaaS platform for companies

A web-based platform to increase productivity, decrease cycle times, accelerate time to market, and protect institutional knowledge.

Thousands of organizations around the globe use Stack Overflow for Teams

Capture your company’s knowledge and context in a discoverable format to unblock your team

Increase productivity

If somebody somewhere has the right answer, suddenly you have it too. Collaborate better in a remote-first world.

Accelerate time to market

Shorten the time between initial idea and complete product. Take delays and misinformation out of the equation.

Protect institutional knowledge

People come and people go, but if you capture their contributions in one central place, that expertise sticks around.

Ensure your company stays on course

Here are just a few types of technologists that we help.

DevOps engineers

Shipping new products and features requires teamwork and coordination. Forget checklists and long docs no one ever reads.

Data scientists

Business decisions are better when backed by data. Give visibility to the data that support your strategies.

Software engineers

Help engineers be more efficient and streamline knowledge sharing using a tool they already love and trust.

Support teams

Level up your support by providing information to your customers using a natural interface: questions and answers.

Engineering leaders

Help your team get the information they need to do their job — reduce burnout and help engineers grow and learn together.

Always free up to 50 teammates

Basic

Up to 250 teammates

Business

Enterprise

Integrates with and improves other tools

All plans come with integrations for ChatOps tools Slack & Microsoft Teams in order to cut down on pings, limit distractions and make the tools even more powerful. Business and Enterprise customers get access to Jira, GitHub & Okta integrations.

Robust read and write API

Single sign-on with AD or SAML

Your own customer success representative

99.5% uptime SLA and priority support

Stack Overflow for Teams has been a resource for our entire company. Not only for developers to solve problems, it’s also enabled our sales field to answer technical questions that help them close deals.

Engineers should help solve the hardest questions, the unknowns, where being familiar with how the product was built is essential. But we don’t want to keep answering solved problems over and over again. That’s where Stack Overflow for Teams really helps.

As we started to use [Stack Overflow for Teams] and saw how nice it was to have a repository of information, we started to see it spread to other teams. Our customer support team started using it, our people success team started using it, next thing we knew, we had [Slack] integrations all over the place.

What we love about Stack Overflow for Teams is that it’s a very dynamic tool…there’s just so many ways to use this as a liaison between different teams and different knowledge bases.

Additional products that reach and engage developers & technologists…

Reach the world’s largest audience of developers and technologists

Connecting communities with the specific technologies they use the most

Build your employer brand

Explore technical topics and other disciplines across 170+ Q&A communities

From Server Fault to Super User, much of the Stack Exchange network continues our mission to empower the world to develop technology through collective knowledge. Other sites on the Stack Exchange network further encourage knowledge sharing across topics such as cooking and medicine.

Build a private community to share technical or non-technical knowledge.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.5.24.43458

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *