0

I have a site that displays (or that's the plan at least) content dynamically, but it has some problems. When I open the site for the first time and click on a link, it loads the content dynamically. When I go back and press a link again, it reloads the whole site. I feel like I'm missing something important, what can it be?

Ajax:

$(document).ready(function () {
    var container = $('#content');

    $('a').click(function (e) {
        e.preventDefault();
        var url = $(this).attr('href');
        //$('#content').hide('fast');
        history.pushState({path: url}, null, url);
        container.load(url);
        return false;
    });

    $(window).bind('popstate', function (event) {
        var state = event.originalEvent.state;

        if (state) {
            container.load(state.path);
        }
    });

    history.replaceState({path: window.location.href}, '');
});
Milen Pivchev
  • 1,417
  • 2
  • 16
  • 29

2 Answers2

1

It happens because you replace the content and the links are no longer bound to the events you added. You need to either rebind the events or use event delegation.

So the solution with event delegation is to replace

$('a').click(function (e) {

with

container.on("click", "a", function (e) {
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

When you load the page for the first time, jQuery binds the "click" function to your a element. However, the dynamic content is loaded AFTER jQuery has done the binding. Since the a tags in the dynamic portion did not exist on the original document load, the jQuery code is not applied to them.

To fix this problem, use on. As in:

 $('a').on('click', function (e) { ...

This is a more dynamic binding. Instead of binding to the a tags that are present when the page is loaded, it binds the action to any a tag that comes a long.

In some situations I've also seen that you have to move this binding outside the $(document).ready() function.

Hope that helps.

Thornview
  • 151
  • 3
  • In your answer `$('a').on('click'` is exactly what the OP has. It is still binding to the element, no event delegation. – epascarello Sep 18 '15 at 19:15