Wige
Wige

Reputation: 3918

My script works fine on static content, but breaks when the content is changed via AJAX - jQuery

I am writing a custom calendar, that consists of two parts, one div showing the month grid, and a second div showing the events for the selected date. The current month's calendar grid loads automatically, and the display of daily events works correctly. However, when the user clicks the button to view the next or previous month, clicking on the dates no longer works. Also, changing the month no longer works on the dynamically-loaded calendar.

This is the jQuery code I am using:

<script type="text/javascript">
    $(document).ready(

    function() {
        $('div.calendar_events').text('To view the events on any of the highlighted dates, simply click the date.');
        $('div.number').click(

        function(e) {
            e.preventDefault();
            var theDate = $(this).attr('id').split('-');
            $('div.calendar_events').load('ajax/calendar_events.php?month=' + theDate[1] + '&day=' + theDate[2] + '&year=' + theDate[3]);
        });
        $('a.changemonth').click(

        function(e) {
            e.preventDefault();
            var theDate = $(this).attr('id').split('-');
            $('div.calendar').load('ajax/calendar_view.php?month=' + theDate[1] + '&year=' + theDate[2]);
        });
    });
</script>

Upvotes: 1

Views: 77

Answers (2)

Anurag
Anurag

Reputation: 141859

Don't setup the events directly using click. Use live instead.

$('div.number').live('click', function() { .. });

When the new AJAX content loads, the new content replaces the old and also wipes out all event handlers you previously attached to that replaced content using bind or its shortcut methods such as click, change, etc.

Live event handlers, on the other hand, are added to the document and due to the event bubbling in the DOM, all events eventually reach up to the document (which you never replace, or ideally should never replace :), so you can think of document as a safe-haven for adding events.

Also checkout delegate which is another way to make use of event bubbling, especially if you are a performance freak.

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382656

Use the live() method of jQuery instead of click for any content that is generated dynamically, here is an example:

$('selector').live('click', function(){
   // your code....
});

.live()

Attach a handler to the event for all elements which match the current selector, now or in the future.

Upvotes: 1

Related Questions