SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict jasongr's Avatar
    Join Date
    Jul 2004
    Location
    usa
    Posts
    371
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    changing the onclick event in javascript

    Hi people

    I have the following code:
    Code:
    <script language="JavaScript">
    function func1() {
         alert("func1 invoked");
    }
    
    function func2() {
         alert("func2 invoked");
    }
    
    function changeFunction() {
        var img = document.getElementById('img');
        if (window.addEventListener) { 	// Mozilla, Netscape, Firefox
           img.addEventListener('click', func2, false);
        }
        else {	// IE
           img.attachEvent('onClick', func2);
        }
    }
    </script>
    <img id="img" src="test.jpg" width="10" height="10" onClick="func1();"></img>
    when the image is clicked with the mouse, function func1 is invoked as expected.
    When I call function changeFunction, I want to change the code that is invoked when the image is clicked from func1 to func2. Instead, both are invoked because addEventListener and attachEvent add an additional handler instead of setting one.
    I am looking for a way to change the handler from one function to another.
    Can anyone think of a solution probably using removeEventListener?

    regards

  2. #2
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by jasongr
    I am looking for a way to change the handler from one function to another.
    Can anyone think of a solution probably using removeEventListener?
    Have you tried just setting any existing handler to null?
    Code:
    function changeFunction() {
        var img = document.getElementById('img');
        img.onclick=null;
    
        if (window.addEventListener) { 	// Mozilla, Netscape, Firefox
           img.addEventListener('click', func2, false);
        }
        else {	// IE
           img.attachEvent('onClick', func2);
        }
    }

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    the IE equivilent to removeEventListener is detachEvent.

    if(element.detachEvent){
    element.detachEvent('onclick',functionref);
    }
    else if (element.removeEventListener){
    element.removeEventListener('click',functionref);
    }
    else element.onclick='';


Bookmarks

Posting Permissions

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