Why won't innerHTML allow me to write an onclick event?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • spheric kinetic
    New Member
    • Jan 2011
    • 1

    #1

    Why won't innerHTML allow me to write an onclick event?

    Code:
    document.getElementById('productThumbs').innerHTML=
    
    "<p>Product 1</p>
    <p>Description of product 1</p>
    <img src='images/thumbs/product1.png'
    class='image'
    onclick='changepic('images/product1.png');'
    />";
    The contents of the <p> tags, and the image are displayed correctly. The onclick event isn't triggered.

    Is there any way to discover if the class of 'image' has been applied to the image? And why doesn't the onclick function work?

    Thanks
  • Oralloy
    Recognized Expert Contributor
    • Jun 2010
    • 988

    #2
    spheric,

    I'm shooting from the hip a little bit here.

    Have you tried changing the "onclick" call to simply invoke the alert method? That way you can check whether the event is failing, or if the code is failing.

    If the event is failing, you're going to have to add the onclick event after the fact, by starting with
    Code:
    document.getElementById('productThumbs')
    and then selecting out the img element by going to the childNodes
    Code:
    document.getElementById('productThumbs').childNodes[5]
    (NOTE: you may have to juggle the index a little to get the node number correct. I am not highly practiced in this regard, so you'll have to be patient with me)
    And, finally adding an event handler...
    Code:
    document.getElementById('productThumbs').childNodes[5].onclick = function(){alert('test me');}
    As I said, just a sketch of how to get there.

    Good Luck!
    Oralloy

    Comment

    • Rabbit
      Recognized Expert MVP
      • Jan 2007
      • 12517

      #3
      Are the line breaks simply for our benefit?

      Comment

      • Oralloy
        Recognized Expert Contributor
        • Jun 2010
        • 988

        #4
        spheric,

        I also noticed that you have what looks like a syntax problem in your innerHTML.

        Specifically, the quoting of the argument to changepic.

        Try changing the quoted argument to double quotes, like so:
        Code:
        document.getElementById('productThumbs').innerHTML= 
          "<p>Product 1</p><p>Description of product 1</p><img src='images/thumbs/product1.png' class='image' onclick='changepic(\"images/product1.png\");' />";
        Cheers!
        Oralloy

        Comment

        Working...