Search code examples
jqueryjquery-load

jquery load with variable


With the following script I load a HTML document into a div-container and show it. With the variable "x" I avoid that the document is reloaded with every click on the button.

The function to hide the container is missing here, as it has nothing to do with my question.

x = 0;
$('.button').click(function () {
    if (x == 0){
        $('.box').load('article.html', function () {
            x = 1;
            $('.box').fadeIn();
        });
    }else{
        $('.box').fadeIn();
    }
});

My question is, how do I have to change the script, if I have more buttons that load different documents?

The variable "x" has to work individually for all the buttons. Is there something like "this.variable" or am I wrong and I have to come up with something completely different?


Solution

  • I would define the document to load in a data attribute. For example:

    <span class="button" data-doc="article.html">Load article</span>
    

    Then:

    $('.button').click(function(){
        var $this = $(this),
            $box = $('.box'),
            loaded = $this.data('loaded'),
            doc;
    
        if (loaded) { 
            $box.fadeIn();
            return; 
        }
    
        doc = $this.data('doc');
    
        $box.load(doc, function () {
            // mark it as being loaded
            $this.data('loaded', true);
            $box.fadeIn();
        });
    });