1

I am sure this has something to do with clone() but I could not find anything on it. My problem is that I am adding in some HTML with anchors. Those anchors should respond to click() and then start an ajax call. I can't seem to stop the anchors default event from working on the $('.term a').

(function($) { 
$(document).ready(function() {
var item = '#main-menu li';
var http_addy = 'http://windowsdeveloper.loc';
// voacabulary id is set in the menu. If one is found then load the terms to the   menu
$('*[id*=vocabulary]:visible').each(function() {
            var voc_id = $(this).attr('id').split('-');
            var parent_li = $(this).parent('[class^=menu-]');
            $.get(http_addy + '/category/content/term_list/' + voc_id[1], function(data) {
                    $(parent_li).append(data);
            });
     });
   // use this to get the terms nodes
    $('div.term a').click(function(event){
            var url = $(this).attr('href');
            $.get(url, function(data) {
                    $('#term-nodes').append(data);                      
            });
            return false;
    });

    $(item).mouseenter(function(event){
        // Styles to show the box
            $(this).children('.vocabulary').show();
        }       
    );
    $('.navigation').mouseleave(
        function() {
            $('#main-menu li').children('.vocabulary').hide();
        }
    );
});
})(jQuery);



<ul id="main-menu" class="links inline clearfix main-menu">
<li class="menu-1050 first">
<a id="vocabulary-3" href="/newsarticletopics/windowsdeveloper">Articles</a>
<div id="term-nodes"></div>
<div id="voc-3" class="vocabulary" style="display: none;">
<div id="term-12" class="term">
    <a href="/category/content/term_nodes/12">Serien</a>
</div>
</div>
</li>
Carl McDade
  • 634
  • 9
  • 14

2 Answers2

4

It is because you are loading some content dynamically and updating the DOM. You should use jQuery on to bind your click event like this

// use this to get the terms nodes
$(document).on("click",".term a",function(event){
        event.preventDefault();
        var url = $(this).attr('href');
        $.get(url, function(data) {
                $('#term-nodes').append(data);                      
        });           
});

jQuery on works for current and future elements in the DOM. on is available from jQuery 1.7+ onwards. If you are using a previous version than that, you should consider live

Shyju
  • 214,206
  • 104
  • 411
  • 497
0
$("selector").on("click", function(e){

 // Do some code here

});

If you are using an older version of jQuery you can use .delegate()

$("selector").delegate("click", function(e){

  // .delegate() takes the parameters a bit differently i think , correct me if i am wrong
 // Do some code here

});

Event binding on dynamically created elements?

Community
  • 1
  • 1
Arif
  • 1,601
  • 2
  • 21
  • 34