0

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?

2 Answers 2

1

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();
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this solution. I've never worked with the data attribute so far.
you're welcome! I've found it to be very handy. jQuery will even deserialize json that you put in there (example).
0

Using jQuery one() event handler you only use an event handler once.

$('.button').one('click', function () {
    $('.box').load('article.html');
});
$('.button').click(function () {
   $('.box').fadeIn();
});

1 Comment

Didn't know there is one() in jquery. It's interesting but I think in my case it's not the right choice because I won't be able to load the content of button 1 again after I clicked on another button and the box contains other content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.