Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jul 2008
    Location
    Peterborough - UK
    Posts
    63
    Thanks
    4
    Thanked 9 Times in 9 Posts

    How to get all event Listeners

    I'm attaching events to buttons on my page using the following code:
    Code:
    			if(document.attachEvent)
    			{
    				theButton.attachEvent('onclick', function(e){button(e)});
    			}
    			else if(document.addEventListener)
    			{
    
    				theButton.addEventListener('click', function(e){button(e)}, false);
    			}
    			else
    			{
    				theButton.onclick = function(e){button(e)};
    			}
    however, some of these elements already have events attached (up to 2 or 3).

    Is there a way to access all the events attached to an element, and loop through them?

    I'm thinking a method similar to this:

    Code:
    function removeEvents(element)
    {
    	for(i=0; i<element.events.length; i++)
    	{
    		element.removeEventListener(events[i].type, events[i].function, false)
    	}
    }
    Of course, I just made all that last code up, but is there somthign of that ilk I can use?

  • #2
    Senior Coder shyam's Avatar
    Join Date
    Jul 2005
    Posts
    1,563
    Thanks
    2
    Thanked 163 Times in 160 Posts
    sadly, no
    You never have to change anything you got up in the middle of the night to write. -- Saul Bellow

  • #3
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,315
    Thanks
    29
    Thanked 279 Times in 273 Posts
    Quote Originally Posted by Mikebert4 View Post
    Code:
    function removeEvents(element)
    {
    	for(i=0; i<element.events.length; i++)
    	{
    		element.removeEventListener(events[i].type, events[i].function, false)
    	}
    }
    Of course, I just made all that last code up, but is there somthign of that ilk I can use?
    If your intent is to simply remove all event listeners from an element, you can do that by using cloneNode; DOM2 Events event listeners are not copied when cloneNode is used.

    Code:
    var new_element = old_element.cloneNode(true);
    old_element.parentNode.replaceChild(new_element, old_element);
    new_element.addEventListener("click", function_reference, false);
    I believe that attachEvent persists even when an element is cloned though, so I’m not sure what you would do for Internet Explorer users.
    For every complex problem, there is an answer that is clear, simple, and wrong.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •