Deselecting an element in jQuery

Posted by Michael Itzoe on Stack Overflow See other posts from Stack Overflow or by Michael Itzoe
Published on 2010-06-07T14:07:49Z Indexed on 2010/06/07 14:12 UTC
Read the original article Hit count: 178

Filed under:

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.

© Stack Overflow or respective owner

Related posts about jQuery