mujaffars
mujaffars

Reputation: 1479

On Mobile device jQuery Touch select div's in random order

On Mobile device I want to select specific div w.r.t. touch ie. when user touch on first div and touchmove to 3rd div then these both div's need to be selected. Like vise the order can be random 1 3 2 4, 1 2 3 4

The attached image will give better understanding

1 3 2 Selection

1 3 2 Selection

1 2 3 selection

enter image description here

I have also created jsfiddle for the same with what I have done till. You can check it at jsfiddle. I am using jquery mobile also trying to use touch and touchmove events but it's not working as per my requirement.

Please help me in this, Thanks

Upvotes: 0

Views: 502

Answers (1)

pleinx
pleinx

Reputation: 626

Its not really clear (for me) what you want. Here is a really simple attempt for you which maybe will help your self to solve your issue.

Checkout this Snippet

EDIT: Updated, now works also which (v)touchmove

$(function() {
  $(".section").on('vclick', function(e) {
    $('.logs').html('eventType: ' + e.originalEvent.type);
    $(this).addClass('green');
    toHighlightElements($(this), $(".section"));
  })

  $(".sections-wrapper").on('vmousemove', function(e) {
    $('.logs').html('eventType: ' + e.originalEvent.type);
    
    var $target;
    if(e.originalEvent.type === 'touchmove') {
      e.preventDefault();
      $target = getActiveElement($(".section"), e.clientX, e.clientY);
      if(typeof $target === 'undefined') {
        return;
      }
    }
    else {
      $target = $(e.target);
    }
    
    toHighlightElements($target, $(".section"));
  });
  
  function toHighlightElements($current, $overall) {
    for (var i = 0 ; i <= $current.index() ; i++) {
     $overall.eq(i).addClass('green');
    }
  }
  
  function getActiveElement($overallElements, x, y) {
      return $(document.elementFromPoint(x, y));
  }  
  
  $('.reset').click(function() {
    $(".section").removeClass('green');
  });
});
.section {
  width: 50px;
  height: 50px;
  border: 1px solid black;
  background-color: grey;
}

.green {
  background-color: green !important;
}

.allowLeft {
  float: left;
}

.sections-wrapper {
  background: red;
  width: 105px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js">
</script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>

<div class="sections-wrapper">

  <div class="section allowLeft">
    1
  </div>
  <div class="section allowLeft">
    2
  </div>

  <div class="section allowLeft">
    3
  </div>
  <div class="section allowLeft">
    4
  </div>
  
   <br style="clear: both" />
</div>
<br><br>
<button class="reset">
reset
</button>

<div class="logs">
</div>

Updated also your jsfiddle: https://jsfiddle.net/m03g52ah/12/

Upvotes: 0

Related Questions