right click to edit div

4

I try to make the div editable but the first attempt does not work, then if it works, what is the error?

  

try it out by clicking on the phrase

var app = angular.module('plunker', []);

app.directive('rightClick', function() {

  document.oncontextmenu = function(e) {
    if (e.target.hasAttribute('right-click')) {
      return false;
    }
  }

  return function(scope, el, attrs) {
    el.bind('contextmenu', function(e) {
      document.getElementById('op').contentEditable = 'true';
    });
  }

});



app.controller('MainCtrl', function($scope) {

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.js"></script>
<script src="app.js"></script>


<body ng-app="plunker" ng-controller="MainCtrl">
  <div id="op" right-click alert="You right clciked me">Right click me</div>
</body>
    
asked by hubman 23.08.2017 в 03:48
source

1 answer

6

The problem is that when you click with the right button, you are making the div editable (initially it was not) by adding contentEditable ... but that's it. That it be editable, does not mean that it automatically enters the edition, for that you have to press a second time (which is the behavior you see).

If you want to make the div click to make editable AND enter the edit, then in addition to putting the contentEditable you should focus the element (with focus ). You just have to add a line of code:

document.getElementById('op').focus(); 

Here you can see it working:

var app = angular.module('plunker', []);

app.directive('rightClick', function() {

  document.oncontextmenu = function(e) {
    if (e.target.hasAttribute('right-click')) {
      return false;
    }
  }

  return function(scope, el, attrs) {
    el.bind('contextmenu', function(e) {
      document.getElementById('op').contentEditable = 'true';
      document.getElementById('op').focus();
    });
  }

});



app.controller('MainCtrl', function($scope) {

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.js"></script>
<script src="app.js"></script>


<body ng-app="plunker" ng-controller="MainCtrl">
  <div id="op" right-click alert="You right clciked me">Right click me</div>
</body>
    
answered by 23.08.2017 / 05:52
source