1

I am adding a link button on page load

Like

$(function(){
    $("#nav_container").append('<a id="testID" href="#">Click on me</a>');

    $("#testID").bind("click",function(){
        alert("hi");
    });
});

But Alert is coming on click of Link

3 Answers 3

3

for dynamically added DOM elements, you'll need to use .on() as following:

$(document).on('click', '#testID', function(){
    alert('hi');
});

hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

$("#nav_container").on("click","#testID",function(){
    alert("hi");
});

Comments

1

For dynamically elements, we should use $.on as suggested by others. But in your case, it should work without using $.on. The reason it does not work it your case because of <a> tag default action to reload, try event.preventDefault();

$(function(){
    $("#nav_container").append('<a id="testID" href="#">Click on me</a>');

    $("#testID").bind("click",function(event){
        event.preventDefault();
        alert("hi");
    });
});

Or better as suggested by others to use $.on:

$("#nav_container").on('click', '#testID', function(event){
    event.preventDefault();
    alert('hi');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.