www.webdeveloper.com
Results 1 to 3 of 3

Thread: Dynamic DOM event assignment

  1. #1
    Join Date
    Sep 2009
    Posts
    2

    Question Dynamic DOM event assignment

    Hello everyone,
    so i figured out how to dynamically assign functions to DOM objects, but I am having a problem, I am trying to do next:

    for(k=0;k<5;k++)
    {
    string="element"+k; //i have <img>s in html with ids: element1, element2, ...
    document.getElementById(string).onClick = function(){ showAlert(k) };
    }

    Function executes just fine, the only thing I get not what I want,
    I would like to assign functions as follows:
    showAlert(1), showAlert(2), ... to element1, element2, ...
    and I get
    showAlert(k), showAlert(k), ... to element1, element2, ...

    Obviously, I need to pass the value of k, but I am not sure what is proper syntax in this case.
    I tried passing k.valueOf() but it does not work for some reason.

    Thank you very much!!!

  2. #2
    Join Date
    Aug 2007
    Posts
    3,767
    Code:
    for(k=0;k<5;k++)
    {
    string="element"+k; //i have <img>s in html with ids: element1, element2, ...
    document.getElementById(string).onClick = (function(){
    function(){ showAlert(k) };
    })();
    }
    That works, because of closures.

    Also, if they are all in a container element, you can do this.
    Code:
    <div id="whatever">
    <div id="el1"></div>
    etc.
    </div>
    Code:
    document.getElementById("whatever").onclick = function (e) {
    var e = e || window.event.
    var t = e.target || e.srcElement;
    alert(t.id);
    };
    Obviously it will need manipulation of the id if you want to have just the number, but you can add and remove elements at your will with that element, and the onclick will work on each just the same.
    Great wit and madness are near allied, and fine a line their bounds divide.

  3. #3
    Join Date
    Sep 2009
    Posts
    2
    Thank you for your routine,
    I see what its doing, getting id of the event that triggered function
    I think that could be better and more flexible approach

    I guess I will use this quick fix for now:

    for(k=0;k<5;k++)
    {
    string="element"+k; //i have <img>s in html with ids: element1, element2, ...
    document.getElementById(string).onClick = (function() showAlert(string.charAt(7)) };
    })();
    }

    I will update my code to use your approach eventually. Thank you for the advise

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles