Bastian
Bastian

Reputation: 5855

jquery how to disable onclick globally while executing a function?

I have a html menu with links that load the main content of the page through ajax. The href links in the menu are empty and the content loads with onclick bound functions:

<a href="#" onclick=home_link()>
    <i class="icon-home"></i>
    <span>Home</span>
</a>

function home_link() {
    $.ajax({
        url: 'home.html',
        dataType: 'html',
        cache : false,
        success: function(html) {
            $('#content_div').append(html);
        }
    });

I have a few links like that in the menu and it works ok if I click them one by one but if I click another link while one is already loading then unwanted things happen, like various contents go into the <div>.

I would like to disable the onclick globally while the function executes and then reenable it or something equivalent that prevents clicking on other links while one is loading.

Upvotes: 0

Views: 182

Answers (1)

Martijn
Martijn

Reputation: 16103

A simple approach would be to add a div overlay, that prevents all clicks in the website. Make it show when you trigger the click, and hide it when the ajax is done:

#disableDiv{
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 10001;
}

That div would be inserted right before the </body> tag. I've read about an IE problem today, which allowed the underlying element to trigger click events. The solution is adding a background. If you dont want a background, you can add the 2nd line, otherwise leave it:

background: #CCC;
opacity: 0; /* 0.5 would be nice with this color too */

Upvotes: 1

Related Questions