Santosh
Santosh

Reputation: 3837

click event working only for the first time jquery

Below code work for the first time after refreshing the page. But when I try to click again it doesn't work.

After clicking on the element it goes to the next page (detail page) and when it come back, the click event doesn't work.

getNewsCategoryloop: function(dataMap){
    var _this = this;
    var text;

    text  = "<div id=\"repeat_get_list_of_category\">";
    for(key in dataMap) {
        text += '<div class="gallery_wrap col-2">\
                    <div class="gallery_view full_image" id="cat'+key+'">\
                        <img src="assets/img/news/athletics_img.jpg" alt="athletics">\
                        <span class="gallery_title">'+ (dataMap[key].field_saf == null ? 'no title' : dataMap[key].field_saf) +'</span>\
                    </div>\
                </div>';
                $(document).on('click', "#cat"+key, function(){
                    _this.getNewsbyCategoryName("#cat"+key);
                })
    }
 text+= "</div>";
 $("#getListOfNewsCategorylist").html(text);            
},  

Upvotes: 2

Views: 1185

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

Put this code:-

$(document).on('click', "#cat"+key, function(){
  _this.getNewsbyCategoryName("#cat"+key);
})

Outside of the whole function itself and change it like below:-

$(document).on('click', ".gallery_view", function(){
  app.getNewsbyCategoryName($(this).attr('id'));
})

So code need to be:-

getNewsCategoryloop: function(dataMap){
    var _this = this;
    var text;

    text  = "<div id=\"repeat_get_list_of_category\">";
    for(key in dataMap) {
        text += '<div class="gallery_wrap col-2">\
                    <div class="gallery_view full_image" id="cat'+key+'">\
                        <img src="assets/img/news/athletics_img.jpg" alt="athletics">\
                        <span class="gallery_title">'+ (dataMap[key].field_saf == null ? 'no title' : dataMap[key].field_saf) +'</span>\
                    </div>\
                </div>';

    }
    text+= "</div>";
    $("#getListOfNewsCategorylist").html(text);         
};
$(document).on('click', ".gallery_view", function(){
   app.getNewsbyCategoryName($(this).attr('id'));
})

Upvotes: 4

Related Questions