tags:

views:

59

answers:

3

I'm having trouble firing a click event on an . When insertIntoInsertHolder() is called it adds a link to the content of div#swf_insert_holder - I then create the click event just below. However the event doesn't fire.

$javascript = "javascript:;";
$swf_insert_box_link = "swf_insert_box_link";

echo "

function insertIntoInsertHolder( filename ) {   
$('#swf_insert_holder').append('<a href=" . $javascript . " class=" .     $swf_insert_box_link . ">go</a>');
//produces: <a href="javascript:;"    class="swf_insert_box_link">go</a>            
    }

$('a.swf_insert_box_link').click( function() {
alert('hello!!'); //for testing     
});

Thanks in advance!

+1  A: 

It also has to be noted, that event handlers are attached to existing elements. So, when your 'click' event is attached to a.swf_insert_box_link, the element should exist. In order to have event attached to the given existing selector and for any new elements matching the same selector, user live() - http://api.jquery.com/live/

Victor Farazdagi
A: 

Using this will cause it to work:

<?php
$javascript = "javascript:;";
$swf_insert_box_link = "swf_insert_box_link";

echo <<<JS
function insertIntoInsertHolder( filename ) {   
  \$('#swf_insert_holder').append('<a href="$javascript" class="$swf_insert_box_link">go</a>');
  // produces: <a href="javascript:;" class="swf_insert_box_link">go</a>            
}

\$('a.swf_insert_box_link').live('click', function() {
  alert('hello!!'); //for testing     
});
JS;
?>

The important parts were #1, fixing all PHP syntax errors and #2, using live instead of click so you can define the event callback before the element actually exists.

Doug Neiner
when I try <<<JS and close it with JS; I get a syntax at ?> at the last line of the file (its got a lot more stuff in it. If I could use <<<JS that would be godly.
Nicholas Reed
@unknown There can be no whitespace (tabs, spaces, etc) between the final `JS;` and the start of the line. Otherwise it will not know the heredoc ended (The heredoc is the `<<<JS ... JS;`)
Doug Neiner
A: 

element must exist before attaching event listeners. you can do it with live() function instead of click() (requires jquery 1.3+), or bind it while creating element, like this:

function insertIntoInsertHolder( filename ) {   
    $('#swf_insert_holder').append(
        $('<a>')
            .attr('href', '<?php echo $javascript; ?>')
            .addClass('<?php echo $swf_insert_box_link;?>')
            .text('go')
            .click(function() { alert('hello!!'); });
    );
}
parserr