Deselecting an element in jQuery
- by Michael Itzoe
I have a collection of span elements. In the code I have a global variable that represents the "selected" object. Using the click event when a span is clicked I reset the object's class, reset the global variable, then set the object to the variable and change its class (to make it "highlighted"). This effectively toggles selection when clicking an object.
var currentItem = null;
$( ".item" ).click( function() {
if( $( this ).hasClass( "selected" ) ) {
$( this ).removeClass( "selected" )
currentItem = null;
} else {
if( $( ".item" ).hasClass( "selected" ) ){
$( ".item" ).removeClass( "selected" )
}
$( this ).addClass( "selected" );
currentItem = $( this );
}
} );
What I'd like to be able to do is unselect when clicking on an empty area of the page. I tried creating a click event on the body object, but that overrode the span click event so nothing was selected. I'm a complete jQuery noob and not sure where to go with this.