Home  >  Article  >  Web Front-end  >  How to Create a Depressed Toggle Button with CSS and JavaScript?

How to Create a Depressed Toggle Button with CSS and JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 09:39:02458browse

How to Create a Depressed Toggle Button with CSS and JavaScript?

Styling Interactive Toggle Buttons

Creating a toggle button that stays depressed when clicked is not directly achievable with pure CSS. To achieve this effect, a combination of HTML, CSS, and JavaScript is required.

Using HTML and CSS:

Consider using a checkbox as the underlying semantic element. Style it differently based on whether it's checked or not. However, this approach may involve additional HTML and CSS complexity.

Using jQuery:

A better solution is to employ jQuery. Here's a compact function that toggles a button's styling between two states:

<code class="js">$(document).ready(function() {
  $('a#button').click(function() {
    $(this).toggleClass("down");
  });
});</code>

Associated CSS:

To style the toggle button, use the following CSS:

<code class="css">a {
  background: #ccc;
  cursor: pointer;
  border: solid 2px;
  padding: 5px;
}

a.down {
  background: #bbb;
  border-color: #777 #777 #eaeaea #eaeaea;
}</code>

HTML:

Finally, include the jQuery library and use the following HTML snippet to implement the button:

<code class="html"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="button" title="button">Press Me</a></code>

The above is the detailed content of How to Create a Depressed Toggle Button with CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn