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.
Use
event.stopPropagation()in your current handler so thatclickdoesn’t bubble up to the<body>, triggering it’s handler as well, then your approach works, like this:You can view a demo here, one suggestion though, if only one element can be
selecteddo you need to keep track of it? If lookup cost isn’t a factor, you could aways find thecurrentItemby doing$(".item.selected"), simplifying this code quite a bit. I’m not sure how you’re usingcurrentItem, just an option you have 🙂