Question

I have html elements that printed in html page using smarty engine , then printed from jquery

the html which is printed from smarty is

<div id="broadcastsXXX" class="broadcast orginal-broadcast highlightedbroadcast">
   <i class="dogears"></i>
   <div class="content">
   ...
   ...
   </div>
</div>

and the html which is printed from jquery is the same html code which is printed comming from smarty template as shown above.

I want to remove the css class "highlightedbroadcast" when someone clicked on the div which has the class "content" as shown above

so I do the jquery code:

 $(document).ready(function() {
    $('.content').click(function() {        
       $(this).parent().removeClass("highlightedbroadcast");
       var broadcastid = ($(this).parent().attr("id"));
    });   
 });

The function is changing the clicked div parent and remove the class highlightedbroadcast.

when the user clicked on the .content div that is printed from smarty template when page loas its remove the highlightedbroadcast css class without any problem. but if the user clicked on the div .content which has been printed from ajax it will not remove the class and do nothing.

I try to add alert('hi') to the function and it also says hi when the user clicked on the .content div which is comes from smarty and do noting when the user clicked on the div which is printed from ajax.

note that the broadcastsXXX is dynamic as broadcasts123 broadcasts124 .. etc

and this is a real example http://jsfiddle.net/samshannaq/FUK5Z/2/

so is there any solution for this?

Was it helpful?

Solution

.click() will only add event handlers to the current DOM.

If you want jQuery events to also apply to any HTML that is subsequently loaded via AJAX, you need to use the .on() event handler rather than .click():

 $(document).ready(function() {
    $('body').on('click', '.content', function() {        
       $(this).parent().removeClass("highlightedbroadcast");
       var broadcastid = ($(this).parent().attr("id"));
    });   
 });

Either that, or you need to add the click events to HTML that is loaded via AJAX after every AJAX call.

OTHER TIPS

I think you should use 'live', while not just 'bind' or 'click' . When document is ready, the div.content is not rendered at all ( they are rendered through ajax response. ). so change your code to

$(document).ready(function() {
  $('.content').live('click',function() {        
   $(this).parent().removeClass("highlightedbroadcast");
   var broadcastid = ($(this).parent().attr("id"));
  });   
});

may work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top