Search code examples
jqueryajaxjquery-load

return to default content after using load()


I using load() to load content from other page to target element like this:

<div id="container">
 <h1>Example Heading</h1>
 <p>Example content.</p>
 <a href="#" role="button" id="load">Load more</a>
</div>
<a href="#" role="button" id="back">Back to default</a>

jQuery

$(document).ready(function() {  
    $('#load').click(function() {
          $('#container').load('content.html');
    };
});

Result

New Content Back to default

So the question is: How to I get back to default content with button Back without refresh the whole page?


Solution

  • Well there's no way for the "back" anchor button to refresh the page without any code, so no it won't.

    For your problem, you can .clone() the element after the page gets loaded, (clone() basically copies the element contents) and then when you click on load more, it's going to load the html contents and when back to default is clicked, it's going to put the elements we have cloned back to the container. Here's how you do it:

    On:

    $(document).ready(function() { 
    

    Clone the container's elements:

    cloned = $('#container').clone();
    

    When the back button is clicked, put it back into the container:

    $('#back').click(function() {
          $('#container').html(cloned);
    });
    

    One last thing is the load more button won't be triggered again because it has been dynamically put back after being replaced by some html. So the click handler is not attached to it, so change your load more click event to:

    $(document).on('click','#load',function() {
          $('#container').load('content.html');
    });
    

    .on() attaches event handler to dynamically created elements.

    Here's a demo:

    DEMO