sugan Posted September 25, 2007 Share Posted September 25, 2007 hii'm creating an application where i would like to give users an option to display the HTML element information when they click the elements using mouse.The page may contain many elements and i want to find the element first and then it's info when it's was clicked by the mouse. I know how to fetch all the info related to the element once i got the element/object .. but i struck back at the point where i've to find which element was clicked..I don't want to add onclick function call to each and every element i create (eventually the pages are already created) by just including the external js file to any of the page i should able to accomplish this..Please help me Link to comment Share on other sites More sharing options...
jesh Posted September 25, 2007 Share Posted September 25, 2007 You can put an onclick event listener on every element in the document by using this: document.onclick = myClickHandler; Alternatively, if you only want to add the onclick listener to div elements with a classname of "MyClickyDiv", you could do something like this: var divs = document.getElementsByTagName("div");for(var i = 0; i < divs.length; i++){ if(divs[i].className == "MyClickyDiv") { divs[i].onclick = myClickHandler; }} Then, once you have then handler listening to the onclick events, your function could look like this: function myClickHandler(e){ // Many browsers pass a reference to the // event directly to the event handler. IE does // not, so we have to derive it e = (e) ? e : window.event; // Different browsers create different events, so // to get the element that created the event, we // have to do something like this. var element = (e.target) ? e.target: e.srcElement; // Now "element" is a reference to the element that // sent the event. Do something with it. element.innerHTML += " was just clicked!";} Link to comment Share on other sites More sharing options...
sugan Posted October 9, 2007 Author Share Posted October 9, 2007 Hi,It worked fine.But, I don't want to add onclick function call to each and every element i create (eventually the pages are already created) by just including the external js file to any of the page i should able to accomplish this..so is there any other way to make this ? Pls help!Regards,Sugan Link to comment Share on other sites More sharing options...
Synook Posted October 9, 2007 Share Posted October 9, 2007 Yes, just put document.onclick = myClickHandler; with the relevant function in the external JS file... Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.