jQuery CSS Trigger

This will show you how to toggle a css class with a simple jQuery function. By Ryan Brackett [email protected]

by Ryan Brackett

HTML

In the HTML, I have wrapped both button and drop down box within the same container. By doing this, we can apply the active class ("xactive") to the main container and control the appearance of both button and content box in the active state, all using one jQuery trigger. This puts the heavy lifting on the CSS part, which is good! Woo hoo!
<br/>
<br/>

<div class="container">
    <div class="trigger">Trigger</div>
    <div class="box">Stuff</div>
</div>

CSS

/* GLOBAL CSS */
 body {
    font-family: arial;
    font-size: 12px;
    padding: 20px;
}
::selection {
    background: transparent;
}
::-moz-selection {
    background: transparent;
}

.container {
    color: white;
    text-align: center;
}
.trigger {
    background-color: #316da5;
    cursor: pointer;
    padding: 20px;
    font-weight: bold;
    font-size: 14px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
}
.box {
    padding: 20px;
    height: 100px;
    background-color: #dedede;
    display: none;
    color: black;
}
/* DEMO CSS for XACTIVE */

.container.xactive .trigger {
    background-color: #0e4477;
    -webkit-border-radius: 5px 5px 0px 0px;
    border-radius: 5px 5px 0px 0px;
}
.container.xactive .box {
    display: block;
}

JavaScript

$('.trigger').click(function () {
    $('.container').toggleClass('xactive');
});