kenp
kenp

Reputation: 500

Add a link dynamically with jquery

I'm able to add a link dynamically on my page, but it doesn't seem to be a link recognized by my javascript code :

Javascript code to add the link :

 var myLink = $('<a>',{
                    text: 'My Link',
                    id : 'link-1',
                    href: '#'
                }).appendTo('#book');

Javascript code to access the link :

$("#link-1").click(function () {
            alert('link-1 clicked');
        });

But when i click the new link created, there's no alert.

Do you have an idea how i can resolve the issue ?

Thanks in advance for your help

Upvotes: 0

Views: 1801

Answers (2)

technophobia
technophobia

Reputation: 2629

Here's how you can do this with .on()

$('#book').on("click", "#link-1", function (e) {
    alert('link-1 clicked');
})

Note: This assumes that the #book element was already in the dom when the binding was set.


Update:

Since you're going to be adding other links, you'll need to use a common class to target those anchors:

 var myLink = $('<a>',{
                    text: 'My Link',
                    class : 'my-anchor', // <-- notice I replaced id with class
                    href: '#'
                }).appendTo('#book');

Now you can target bind to those anchors like so:

$('#book').on("click", ".my-anchor", function (e) {
    alert('my-anchor clicked');
})

Important Note: You cannot have duplicate id attribute values in your document - that would invalidate your html and cause unexpected behaviour in your JavaScript.

Upvotes: 1

tribe84
tribe84

Reputation: 5632

You need to create your link before you bind the "click" event, otherwise it will not work.

Alternatively, using jQuery.live to bind to events of elements which might not exist on the page.

example:

$("#link-1").live('click', function () { alert('link-1 clicked'); });

Upvotes: 0

Related Questions