Deselect a selected area with jQuery

226 Views Asked by At

I have the following HTML:

<div class="folders block">
    <div class="ui-widget-content">            
         <table class="folders-list">
             <tbody class="folder">
                  <tr><td style="text-align: center">Папки: </td></tr>
                  <tr class="folder-name"><td><i class="fa fa-folder-open"></i><span>Всички</span></td></tr>          
             </tbody>
         </table>
    </div>
</div>

And the following jQuery:

$(".folder").selectable({
    stop: function() {
        $(".ui-selected", this)
            .each(function() {
                var index = $("table tbody").index(this);   
            });     
    }
});

Everything is fine accept when I want to deselect the selected item. Wherever I click nothing happens. I didn't find anything that could help.

1

There are 1 best solutions below

0
Mosh Feu On

If I understand you correctly, there is no straightforward way to do this, but you can use a trick.

When the user click on somewhere outside the container (.folder) you should do 2 things:

  1. Remove the .ui-selected class of the selected items.
  2. Clear the selected list of the widget's instance.

Note: It's a generic solution so maybe it will conflict with your other code ($('html').click for example) so be careful.

To the code:

$( "#selectable" ).selectable().click(function(event) {
  event.stopPropagation();
});

$('html').click(function(){
  var ins = $( "#selectable" ).selectable( "instance" );
  // clear the selected list
  ins.selectees = [];
  // remove the selected class
  ins.element.find('.ui-selected').removeClass('ui-selected');
});
#feedback { font-size: 1.4em; }
#selectable .ui-selecting { background: #FECA40; }
#selectable .ui-selected { background: #F39814; color: white; }
#selectable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#selectable li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<ol id="selectable">
  <li class="ui-widget-content">Item 1</li>
  <li class="ui-widget-content">Item 2</li>
  <li class="ui-widget-content">Item 3</li>
  <li class="ui-widget-content">Item 4</li>
  <li class="ui-widget-content">Item 5</li>
  <li class="ui-widget-content">Item 6</li>
  <li class="ui-widget-content">Item 7</li>
</ol>