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!