0

I've been trying to piece together various SO answers on this topic but I can't quite figure it out. This answer shows how to select multiple items but I can't figure out how to add the condition of the shift key being pressed.

Dragging over multiple items selects them all, that's great. Clicking single items selects that item, that's great. But If the shift key is pressed, clicking multiple items should select them all, clicking them again should deselect them.

Here's a fiddle.

HTML

<div id="canvas">
    <div class="elemContainer ui-selected" style="position: absolute; top: 50px;
    left: 50px; width: 100px; height: 100px;">     
        <div class="elem" style="position: absolute; width: 100%; height: 100%; 
        background: pink;"></div>
    </div>

     <div class="elemContainer ui-selected" style="position: absolute; top: 50px;
    left: 50px; width: 100px; height: 100px;">     
        <div class="elem" style="position: absolute; width: 100%; height: 100%; 
        background:  coral;"></div>
    </div>
</div>

Javascript

$('#canvas').selectable();

$('.elemContainer').draggable();

// Fix single click selection
$(".elemContainer").click(function() {
    if (!$(this).hasClass("ui-selected")) {
        $(this).addClass("ui-selected").siblings().removeClass("ui-selected");
    }
})
Community
  • 1
  • 1
colmtuite
  • 4,311
  • 11
  • 45
  • 67

1 Answers1

1

See this updated fiddle: http://jsfiddle.net/5ayrW/7/

.click(function(e) {
 if (e.shiftKey) {

Both, click and shift+click now calling a function which adding classes to itself or the siblings.

ggzone
  • 3,661
  • 8
  • 36
  • 59
  • Thanks mate that's awesome. When I shift click on a selected element, it should become deselected. I've been messing with the if statements but I can't figure it out :( – colmtuite Nov 04 '13 at 13:28
  • the problem right now is, that the normal click also applies to the shift + click. just putting the click functions in the shift+click else condition is doing the trick. also i used toggleClass now for the shiftclick which makes it one line smarter. updated the fiddle. – ggzone Nov 04 '13 at 13:52
  • Ah I see. Weird though, now if you drag to select both elements, nothing gets selected..... – colmtuite Nov 04 '13 at 14:00
  • seems like these two (dragable and selectable) conflicting each other. nevermind. jquery is mighty enough to handle this: updated the fiddle with adding a dragable: start function to add a selection. crossbrowsertests are highly recommended here – ggzone Nov 04 '13 at 14:15
  • argh... seems like the multiple selection via crossdrag not working anymore.. but i guess you can fix it somehow. ;) – ggzone Nov 04 '13 at 14:19