SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict
    Join Date
    Jun 2006
    Location
    Durban, South Africa
    Posts
    287
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Associating a function to an event with function parameters

    Hi all

    I am trying to associate a function with an onclick on an element, but I need to be able to pass parameters to the function.

    Does anyone know how to do that?

    This is my code to associate functions to events

    Code:
    function add_event(obj , event_type , func) {
      if(obj.addEventListener) {
        obj.addEventListener(event_type , func , false);
        return true;
      } else if(obj.attachEvent) {
        var r = obj.attachEvent('on' + event_type , func);
        return r;
      } else {
        return false;
      }
    }
    
    function temp() {
      alert('the page loaded');
    }
    
    // usage
    add_event(window , 'load' , temp);
    This would run the temp function when the window has loaded.
    But what if I needed to pass a variable to the temp function.

    Can anyone help please?

  2. #2
    SitePoint Addict
    Join Date
    Jun 2006
    Location
    Durban, South Africa
    Posts
    287
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Haha figured it out

    Code:
    function add_event(obj , event_type , func) {
      if(obj.addEventListener) {
        obj.addEventListener(event_type , func , false);
        return true;
      } else if(obj.attachEvent) {
        var r = obj.attachEvent('on' + event_type , func);
        return r;
      } else {
        return false;
      }
    }
    
    function temp(func_var) {
      alert('the page loaded - ' + func_var);
    }
    
    // usage
    var a_var = 1;
    add_event(window , 'load' , function(){temp(a_var);});
    I created an anonomous function to call the temp function, which can take parameters


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
  •