-4

Example:

div.my{width: 100%;}

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

left click:

div{width: 75%;}

Right click:

div{width: 100%;}

2 Answers2

0

First of all, you should be careful using left click and right click in browsers. Not all browsers support right clicks. If you still want to implement this, the right click can be detected through the oncontextmenu event.

This Stack Overflow post has an example for you in JavaScript.

Basically, you are going to need to script a function that triggers when oncontextmenu occurs. You'll need to access the element via document.getElementById() or similar DOM traversal function. Then change the width via the element's style property in JS.

You cannot access the right click using only HTML and CSS.

Community
  • 1
  • 1
BMcNamara
  • 41
  • 4
0

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>
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Sarbbottam
  • 5,410
  • 4
  • 30
  • 41
  • Strange. Still the answer is down voted. You should up vote and accept the answer it it serves the purpose. – Sarbbottam Jul 20 '14 at 23:39
  • Not my downvote, but code only answers are not liked. – RobG Jul 20 '14 at 23:49
  • I hear you. In the above example, isn't the code sufficient for the explanation. I would certainly add explanation in the future answers. – Sarbbottam Jul 20 '14 at 23:53
  • You can edit your answer to include an explanation, then the down–voter can remove the vote. And "the code is the best documentation" indicates an expectation that reverse engineering intent from code will arrive at the same place, *cf* [*Chinese whispers*](http://en.wikipedia.org/wiki/Chinese_whispers). – RobG Jul 21 '14 at 00:01
  • Added explanation as suggested. – Sarbbottam Jul 21 '14 at 00:10