Reputation: 12608
I have this jQuery script which selects (highlights) and deselects divs based on the item that is clicked...
<script>
jQuery(document).ready(function($) {
$links = $('.property');
$links.click(function(e) {
//Get our variables, simply $(this) and the colour
var $this = $(this),
color = $this.data('col');
//Toggle the active class on this link
$this.toggleClass('active');
//Remove .main on all .test's
$(".slayout").removeClass("main");
$(".product").addClass("trans");
$(".product").removeClass("main");
//Map the active link's data-col with a dot attributes to an array
//Join it up to make a selector
var selector = $links.filter('.active').map(function(){
return "."+$(this).data('col');
}).get().join('');
//Add the class back on to matches
$(selector).addClass('main');
//Finally, prevent the default action
e.preventDefault();
});
});
</script>
How can I modify this so that if no items are selected then a new CSS class is applied to all items. This class should be removed if anything is clicked.
Upvotes: 0
Views: 60
Reputation: 8189
You can test if you have one or more $(selector)
:
var selector = $links.filter('.active').map(function(){
return "."+$(this).data('col');
}).get().join('');
// remove the class added when there was no item selected
$('.allitems').removeClass('myclass');
if ($(selector).length > 0) {
//Add the class back on to matches
$(selector).addClass('main');
} else {
$('.allitems').addClass('myclass');
}
Upvotes: 2
Reputation: 16214
if (selector.length == 0)
// add class to all items
Just do not make .join() before it, or $(selector).length if join is done.
Upvotes: 0