Search code examples
javascriptjqueryhtmlalertify

Alertify / Display message on page load 1 time instead of button click


Here's my current setup. I would like to display the message on a homepage once instead of href link. The latest updates. No luck with the listener I believe:

<script>
function reset() {
    $("#toggleCSS").attr("href", "../themes/alertify.default.css");
    alertify.set({
        labels: {
            ok: "OK",
        },
        delay: 5000,
        buttonFocus: "ok"
    });
}

// ==============================
// Standard Dialogs


var listener = function(e) {
    e.preventDefault();
    $('#el').off(listener);


    $(document).ready(function() {
        reset();
        alertify.alert("Message en français ici / Message en anglais ici");
        return false;
    });

};
$('#el').on('click', listener);
</script>

Solution

  • If you wish to execute the click-triggered behavior only once, and then let #alert behave normally use the $.one('click', ...) method.

    Also make sure you prevent the default behavior by using event.preventDefault()

    This will automatically remove the listener after the first usage.

    The following two are equivalent

    var listener = function (e) { 
        e.preventDefault();
        $('#el').off(listener);
        /* your logic */
    };
    $('#el').on('click', listener);
    

    and

    var listener = function (e) { 
        e.preventDefault();
        /* your logic */
    };
    $('#el').one('click', listener);
    

    Edit

    If you wish to have the logic executed on page load, then use the $(document).ready listener