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

How to Create a Toggle Button with Sass and jQuery?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 02:26:02280browse

How to Create a Toggle Button with Sass and jQuery?

Creating a Toggle Button with Sass and jQuery

If you're looking to create a toggle button that maintains its state on click, you'll need to dive beyond CSS alone.

Semantic Approach

The preferred approach is to use a checkbox, stylizing it according to its checked state. However, this can involve additional elements and complexity.

jQuery Solution

A more efficient method is to employ jQuery and two background images for the different button states.

HTML:

<code class="html"><a id="button" title="button">Press Me</a></code>

JS:

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

CSS:

<code class="css">a {
  background: #ccc;
  cursor: pointer;
  border-top: solid 2px #eaeaea;
  border-left: solid 2px #eaeaea;
  border-bottom: solid 2px #777;
  border-right: solid 2px #777;
  padding: 5px 5px;
}

a.down {
  background: #bbb;
  border-top: solid 2px #777;
  border-left: solid 2px #777;
  border-bottom: solid 2px #eaeaea;
  border-right: solid 2px #eaeaea;
}</code>

This jQuery function toggles the "down" class on the button when clicked. The CSS classes define the background images and border styles for each state.

The above is the detailed content of How to Create a Toggle Button with Sass and jQuery?. 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