Hi there!! I have a paragraph “<p>” element and I want to attach a click event to it. But I want that event to be executed by an object method and I do not know how to do it.
This is an example of what I want to do:
Code:
<html>
<head>
<title></title>
<script type="text/javascript">
var user;
function load()
{
user=new User("john");
user.loadclick();
}
function User(username)
{
this.username=username;
}
User.prototype.loadclick=function()
{
parag=document.getElementById("parag");
//parag.setAttribute("onclick","this.clickFunc()");//does not work
parag.setAttribute("onclick","User.prototype.clickFunc()");//does not work, username undefined
}
User.prototype.clickFunc=function()
{
console.log("in click Func, username="+this.username);
}
</script>
</head>
<body onload="load()">
<p id="parag">the text</p>
</body>
</html>
I want to trigger “clickFunc” each time user click on the paragraph.
Could someone tell me how to do it??
Thank you very much!!!
if (parag.addEventListener) // for Mozilla and friends
parag.addEventListener("click", this.clickFunc, false);
else if (parag.attachEvent) // for IE
parag.attachEvent("onclick", this.clickFunc);
Hi all!! thank you very much for response. seniseven, if I use your solution, the username is undefined. And I have to use the prototype object to create functions in JavaScript.
Do you know other solutions?? thank you very much!
I was suggesting my code to replace only your .setAttribute() method, not particularly for anything else. I did not check your code for the User object you created, for example.
You need to keep in mind that the DOM object (like a paragraph or div or span or any other DOM object) will have the .addEventListener() method in the browser you may be using for debugging.
But if you intend this code to be executed in IE, Chrome, Safari and other browsers, once you finish with yours, you may need to add cross-browser functionality to it especially for people running older versions of IE. The use of .addEventListener() will generate an error for them, which is why you need to know IE's version of it, method .attachEvent(), and why you also need to test your code in all the browsers where it will run. Yes, it is possible. Some people install Win95/98 and WinXP, and a distro of Linux in 3 or 4 virtual machines, then open the browser and your web page to see what gives. Be thorough as a web developer.
Hi seniseven, you are right! I have to add the source code for IE. So this code:
Code:
if (parag.addEventListener) // for Mozilla and friends
parag.addEventListener("click",this.clickFunc.bind(this),false);
else if (parag.attachEvent) // for IE
parag.attachEvent("onclick", this.clickFunc.bind(this));
will be enough, won't it???
Also I have to test the "bind" function on IE. I am affraid it will not work.....
Bookmarks