jQuery addClass example
Change class name on click in jQuery
by John Pisello
HTML
<div id="banner-message">
<h2>
Banner title
</h2>
<p>Banner message goes here. Yes, it goes here. Totally here. Not there, but here.</p>
<button>Change color</button>
<a class="expando" title="expand banner"></a>
</div>
CSS
body {
background: #20262E;
padding: 2rem;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 2rem;
/* font-size: 25px; */
position: relative;
/* text-align: center; */
transition: all 0.5s ease-in-out;
margin: 0 auto;
width: 20rem;
height: auto;
min-height: 6rem;
will-change: width height;
}
#banner-message > h2,
#banner-message > button ,
#banner-message > p {
flex: 0 0 auto;
margin: 0 0 1rem;
/* padding: 0; */
}
#banner-message > p {
flex-grow: 1;
}
#banner-message .expando {
background-color: #0084ff;
background-image: radial-gradient(ellipse at center, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0) 50%, rgba(255, 255, 255, 1) 51%, rgba(255, 255, 255, 1) 100%);
background-size: .5rem .5rem;
border-radius: .25rem;
content: '';
cursor: zoom-in;
width: 1.5rem;
height: 1.5rem;
position: absolute;
bottom: .125rem;
right: .125rem;
transform: rotate3d(1, -1, 0, 0);
transform-style: preserve-3d;
transition: transform 1.5s ease-in-out;
}
#banner-message .expando::before {
background-color: white;
border-radius: .25rem;
content: '';
width: 1rem;
height: .5rem;
position: absolute;
top: 0;
left: 0;
z-index: 10;
}
#banner-message .expando::after {
background-color: white;
border-radius: .25rem;
content: '';
width: .5rem;
height: 1rem;
position: absolute;
top: 0;
left: 0;
z-index: 10;
}
#banner-message.expanded {
width: 600px;
height: 200px;
}
#banner-message.expanded .expando {
cursor: zoom-out;
transform: rotate3d(1, -1, 0, -180deg);
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
JavaScript
// find elements
var banner = $("#banner-message")
var button = $("button")
var expando = $(".expando")
// handle click and add class
button.on("click", function(){
banner.addClass("alt")
})
expando.on("click", function() {
$(this.parentElement).toggleClass('expanded');
})