Is it possible to define a on click event inside an object (oop)?
I’m new to this.
I have been trying the following: (I simplified the code (no CSS of div etc))
function menu_item(menu_name){
this.menu_name=menu_name;
this.create = function(){
$('body').html("<div id=" + menu_name + " />");
};
$('#' + menu_name).on('click',function(){
alert (menu_name);
});
}
menu_item("test");
menu_item.create();
Now when I click on the div with id of the given menu_name,
I want to alert the name (as a test) but this isn’t working…
is this even possible?
Yes, it is possible. However, I can’t see any OOP constructor in your code – you call it as a function.
Your problem seems to be that you have no element with that id when you try to add the event listener, or a call to your
createmethod overwrites it.Use this: