3

Below is the code that dynamically creates an element and attach an onclick event.

var div = document.createElement('div');
div.onclick = function(e){
    console.debug(e);           
}

var parent = document.getElementsByClassName('myid_templates_editor_center_menu');
parent[0].appendChild(div);

How about attaching a right click event?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

5 Answers5

2

The answer to your question consists of two parts:

1) How to attach the right-click event?

Answer: use the contextmenu event.

2) How to attach an event to dynamically created elements?

Answer: the idea is to attach the event to the parent element that will contain your newly created element. The event will propagate along the DOM until it reaches your parent element.

Working Example:

//get parent elements
var elements = getElementsByClassName('myid_templates_editor_center_menu'); 

//attach to the first found parent element
elements[0].addEventlistener('contextmenu', function(e) {
    console.log("right clicked!");
 })
0

You can use contextmenu event

window.onload = function() {
  var div = document.createElement("div");
  div.innerHTML = "right click";
  div.oncontextmenu = function(e) {
    console.debug(e.type, e);
  }

  document.body.appendChild(div);
}
guest271314
  • 1
  • 15
  • 104
  • 177
0

Add

div.oncontextmenu = function(e){
    e.preventDefault();
    console.debug(e);           
}

instead onclick

w.Bala
  • 129
  • 3
0

Working Example

node.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
alert('success! - Right Click');
return false;

}, false);

Codepen : http://codepen.io/mastersmind/pen/WogoVB

mastermind
  • 1,057
  • 1
  • 8
  • 15
-1
var div = document.createElement('div');
div.oncontextmenu = function(e){
    console.debug(e);           
}

var parent = document.getElementsByClassName('myid_templates_editor_center_menu');
parent[0].appendChild(div);
Surya Purohit
  • 1,090
  • 1
  • 9
  • 29