Search code examples
javascriptjqueryhtmljquery-load

jQuery simple loading and unloading content into DIV


I know this question has been asked before but I cannot get the answer I need so I'm going to try to simplify it:

When I click on .LINK, I want the #GRID content to be filled with other divs, so I'm using*:

$(".LINK").click(function(){
    $( "#GRID" ).load('my_linked_file.html .other_divs');
});

So far so good. But now I have a second link, that I want to use to 'revert' this loaded content, to go back to it's original state. I'm just doing the same all over again, but it doesn't seem to work.

$(".LINK2").click(function(){
    $( "#GRID" ).load('my_original_file.html .my_original_divs');
});

I'd be happy to upload a jsfiddle but .load only works on the server. I can upload a jsfiddle for illustration (layout) purposes if that helps?

(*I've seen many people suggesting the hide and show method. But I have plenty of links with plenty of content and I'm assuming doing so will slow down my page quite noticeably)

Any thoughts?


Solution

  • Something like this worked for me:

    <a href="my_linked_file.html" class="LINK">Click Me</a>
    <a href="my_original_file.html" class="LINK2">Click Me 2</a>
    <div id="GRID"></div>
    
    <script type="text/javascript">
    $('.LINK').on('click', function (event) {
        event.preventDefault();
    
        $('#GRID').load($(this).attr('href') + ' .other_divs');
    });
    $('.LINK2').on('click', function (event) {
        event.preventDefault();
    
        $('#GRID').load($(this).attr('href') + ' .original_divs');
    });
    </script>