0

I am calling ajax via jquery in an effort to load an href. The html seems to load correctly. However, the html that is loaded (href) does not actually work. Specifically, I can't figure out why once the link loads via ajax, it doesn't actually do anything when I click it. No errors in firebug, just dead link. Is my .on() method incorrect?

home.html

<html>
<head></head>
<body>
<div id="connections">Placeholder Text</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript">
var uri='home-ajax.html'; //first find out if this is created yet   
var myVar=setInterval(function(){example_ajax_request()},8000); //to do that check for it ev. 8 sec.
function example_ajax_request() {
    $.ajax({
        type: 'GET',
        url: 'home-ajax.html', //checking
        dataType: 'html', //html is content inside home-ajax.html
            success: function() {               
                $('#connections').load('home-ajax.html'); //if home-ajax exists replace connections div with its content
                clearInterval(myVar); //stop the 8 sec. timer
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
    });

}

$('myLink').on('click', function(e) { //using .on to actively bind new href link from ajax()
    document.location.href="http://www.cnn.com";//when href with id='myLink' is clicked, go to www.cnn.com
});
</script>

</body>
</html>

home-ajax.html

<p><a href="#" id="myLink">CNN</a></p>

1 Answer 1

1

That element did not exist on page load, so you can't bind a click function directly to it. You have to delegate the click to a static element.

$(document).on('click', '#myLink', function(e){
    e.preventDefault(); // stop default action
    document.location.href="http://www.cnn.com"; //do work
});
2
  • Thank you! Quick follow up. What would change in your answer if I added another link like: <p><a href="#" id="myLink2">fox.com</a></p>
    – Chris
    Jan 28, 2013 at 18:43
  • 1
    @Crhis it would be #myLink2, but...i all links went to the same place, we could just capture the click on any element that starts with myLink, $(document).on('click', '[id^=myLink]', function(){
    – Ohgodwhy
    Jan 28, 2013 at 18:45

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.