Reputation:
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
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
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
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
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
Reputation: 129
Add
div.oncontextmenu = function(e){
e.preventDefault();
console.debug(e);
}
instead onclick
Upvotes: 0