Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function only once

I've 3 divs (#Mask #Intro #Container) so if you click on Mask, Intro gets hidden and Container appears. The problem is that I just want to load this only one time, not every time I refresh the page or anytime I click on the menu or a link, etc.

How can I do this?

This is the script I'm using for now:

$(document).ready(function(){
    $("div#mask").click(function() {
        $("div#intro").fadeToggle('slow');
        $("div#container").fadeToggle('slow');
        $("div#mask").css("z-index", "-99");
    });
});

Thank you!

like image 209
Carlos Salas Avatar asked Dec 08 '11 09:12

Carlos Salas


Video Answer


1 Answers

You can try using a simple counter.

// count how many times click event is triggered
var eventsFired = 0;
$(document).ready(function(){
    $("div#mask").click(function() {
        if (eventsFired == 0) {
            $("div#intro").fadeToggle('slow');
            $("div#container").fadeToggle('slow');
            $("div#mask").css("z-index", "-99");
            eventsFired++; // <-- now equals 1, won't fire again until reload
        }
    });
});

To persist this you will need to set a cookie. (e.g. $.cookie() if you use that plugin).

// example using $.cookie plugin
var eventsFired = ($.cookie('eventsFired') != null)
    ? $.cookie('eventsFired')
    : 0;

$(document).ready(function(){
    $("div#mask").click(function() {
        if (eventsFired == 0) {
            $("div#intro").fadeToggle('slow');
            $("div#container").fadeToggle('slow');
            $("div#mask").css("z-index", "-99");
            eventsFired++; // <-- now equals 1, won't fire again until reload
            $.cookie('eventsFired', eventsFired);
        }
    });
});

To delete the cookie later on:

$.cookie('eventsFired', null);
like image 103
Yes Barry Avatar answered Nov 15 '22 00:11

Yes Barry