user4621642
user4621642

Reputation:

Attaching Right Click Event on Dynamically Created Elements

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?

Upvotes: 3

Views: 1387

Answers (5)

mastermind
mastermind

Reputation: 1057

Working Example

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

}, false);

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

Upvotes: 0

Surya Purohit
Surya Purohit

Reputation: 1120

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);

Upvotes: -1

guest271314
guest271314

Reputation: 1

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);
}

Upvotes: 0

user6269864
user6269864

Reputation:

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!");
 })

Upvotes: 2

w.Bala
w.Bala

Reputation: 129

Add

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

instead onclick

Upvotes: 0

Related Questions