jQuery Toggle Class on Click

The jQuery toggle() Method is part of the jQuery core and a useful method for toggling between jQuery hide() and show(). In a recent use case, we needed to provide a simple way for a client to see how their site would look with or without background images and so we wrote up a very simply jQuery snippet to Toggle a CSS Background on a button/link click. Here’s how: – 

<a href="#" class="toggle-class">Toggle Class</a>
<style>
.no-bg {
background-image: none;
}
</style>
<script>
jQuery(document).ready(function($) {
$(".toggle-class").click(function () {
$(".target-class").toggleClass('no-bg');
});
});
</script>

The target in this instance is the element with class “target-class” so simply change this to your own target / div. Now when you click the link with class ‘toggle-class’ the element will toggle the class ‘no-bg’ which you can also change to suit your needs.

About the Author
jquery toggle class on click jQuery Toggle Class on Click 0da77002febbfe28d15144a57bbcc2c9 s 180 d mm r g

Glenn

A highly experienced Web Designer / Web Developer (Webflow, WordPress, Weebly & Custom), Front-end / Back-end Developer & New Media Specialist, with extensive knowledge of a wide spectrum of technologies in the Development and Creative Industries, built up over a number of years.