Question

I have been bashing my head against a wall for about 4 hours now trying to figure out why this wont work. I have a program that needs to dynamically write code depending on the number of results from an SQL query.

I am using a jquery lightbox called EasyBox. When it is hard-coded like this, it works:

<body id="body" onload="bodyLoaded()">
<a id="link" href="#test" title="Snowflake" rel="lightbox">Hello</a>
<div id="test" style="display:none; width:320px; height:240px">
    <p>Test Content</p>
</div>    
<script type="text/javascript">
    function bodyLoaded(){
        $('#link').attr('onclick', 'logText("Hello")');
    }
    function logText(message){
        console.log(message);   
    }
</script>

However, when I have the link written dynamically like this, the EasyBox popup does not fire.

<body id="body" onload="bodyLoaded()">
<div id="test" style="display:none; width:320px; height:240px">
    <p>Test Content</p>
</div>
<script type="text/javascript">
    function bodyLoaded(){
        document.getElementById('body').innerHTML+="<a id='link' href='#test' rel='lightbox'>Hello</a>";
        $('#link').attr('onclick', 'logText("Hello")');
    }
    function logText(message){
        console.log(message);   
    }
</script>

Any ideas why this would work? I am pulling my hair out here!

Was it helpful?

Solution

I don't understand why you're not just using jQuery for all of this.

$(function(){
   $('#body').prepend("<a id='link' href='#test' rel='lightbox'>Hello</a>");
   $('#link').click(function(){
      alert("Hello");
   });
});

If the .click() doesn't work, you could also try .live(). Both worked for me in jsfiddle(http://jsfiddle.net/LZxrL/ and http://jsfiddle.net/LZxrL/1/).

Also, why does everyone keep saying there is no element with id='body' when the body element itself has the id of 'body.' Clearly, he wants to add a link to the body.

EDIT: I just read your comment on another post about the issue being the lightbox, not the click event. That DOES change things. I'm not familiar enough with that plugin to comment authoritatively, but I would suspect that the plugin looks for rel="lightbox" when the page loads and any elements added afterward won't be caught. Most plugins have a manual method, something like:

$('#link').lightbox();

OTHER TIPS

I'm not seeing where you are loading the dynamic tags in your script. bodyLoaded() function is looking for anything with id='body' and in your second block of code I don't see any with that id tag.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top