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

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

Patricia Arquette
Release: 2024-11-02 09:39:02
Original
564 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template