Search code examples
javascriptjqueryadditionsubtraction

How I can reduce the length with each left click and right click each increase it?


Example:

div.my{width: 100%;}

<div class="my"></div>

left click:

div{width: 75%;}

Right click:

div{width: 100%;}

Solution

  • Initialize the width of the target as 100 [As mentioned in the post].

    Listen to the mousedown event and determine the mouse button clicked from the which attribute of the event passed to the callback function.

    In the callback function depending on the mouse button clicked add or subtract the desired unit[25 in this case].

    Apply the calculated width to the target.

    Please refer the JSFiddle for working example.

    var elasticDivWidth = 100;
    $('.elastic-div').on('mousedown', function(e) { 
      e.preventDefault();
      if( (e.which == 1) ) {
        elasticDivWidth = elasticDivWidth - 25;
      } else if( (e.which == 3) ) {
        elasticDivWidth = elasticDivWidth + 25;
      }
      $(this).css('width', elasticDivWidth + '%');
    }).on('contextmenu', function(e){
      e.preventDefault();
    });
    .elastic-div {
      height: 200px;
      background: cyan;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="elastic-div"></div>