www.webdeveloper.com
Results 1 to 3 of 3

Thread: Attaching events to dynamic content

  1. #1
    Join Date
    Sep 2009
    Posts
    2

    Angry Attaching events to dynamic content

    I have this code:

    Code:
    var container = document.getElementById( 'container' );
    var url = document.createElement( 'a' );
    
    url.setAttribute( 'id', 'dynamic' );
    url.setAttribute( 'href', 'http://foo.bar' );
    url.innerHTML = 'CLICKME!';
    container.appendChild( url );
    url.addEventListener( 'click', function( evt ) { evt.preventDefault(); alert( 'OK' ); }, false );
    It works fine, but then I add one more line:

    Code:
    container.innerHTML += '<br>';
    and it stops working. The event handler isn't called at all. Why is that?
    Thanks.

  2. #2
    Join Date
    Oct 2003
    Location
    Andover, UK
    Posts
    947
    Invoking the browser's HTML parser after via innerHTML after the initial page load is generally a bad idea, hence the Javascript world moved on to DOM scripting.

    You've already got some createElement stuff going on, so the change needed here shouldn't be too much of a shell-shock for you.

    Change

    Code:
    obj.innerHTML += "<br />";
    for

    Code:
    var br = document.createElement('br');
    container.appendChild('br');

  3. #3
    Join Date
    Sep 2009
    Posts
    2
    This is what I'm using, but I was wondering why the first code didn't work. Thanks

Thread Information

Users Browsing this Thread

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

Tags for this Thread

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