Marc Taylor
Marc Taylor

Reputation: 47

how to stop javascript function after running once?

can someone please show me how i can stop this javascript function after it has ran once? At the moment it just repeats again and again and i only want it to run the once.

I'm still learning javascript, so sorry if its not great.

thanks

<script>
$(function() {
    $(".search_prompt").hide();

    $("#text").focusin(function() {
        $(".search_prompt").show();
    }).focusout(function () {
        $(".search_prompt").hide();
    });
});
</script>

Upvotes: 0

Views: 1534

Answers (2)

bikeshedder
bikeshedder

Reputation: 7487

Unbind the event handler once it has been run:

$(function() {
    $(".search_prompt").hide();
    function show_search_prompt() {
        $(".search_prompt").show();
        $("#text").unbind("focusin", show_search_prompt);
    }
    function hide_search_prompt() {
        $(".search_prompt").hide();
        $("#text").unbind("focusout", show_search_prompt);
    }
    $("#text").bind("focusin", show_search_prompt);
    $("#text").bind("focusout", hide_search_prompt);
});

Working example

http://jsfiddle.net/bikeshedder/JqErw/


JQuery plugin

If you need this several times you could write a JQuery plugin for this:

$.fn.bindRunOnce = function(eventType, eventHandler) {
    this.bind(eventType, function cb() {
        $(this).unbind(eventType, cb);
        eventHandler.apply(this, arguments);
    });
};

$(function() {
    $(".search_prompt").hide();
    $("#text").bindRunOnce("focusin", function(ev) {
        $(".search_prompt").show();
    });
    $("#text").bindRunOnce("focusout", function() {
        $(".search_prompt").hide();
    });
});

Live demo

http://jsfiddle.net/bikeshedder/JqErw/1/


... or you could use one as suggested by salexch.

How could I miss this one? :-)

Upvotes: 0

salexch
salexch

Reputation: 2704

<script>
$(function() {
    $(".search_prompt").hide();

    $("#text").one('focusin', function() {
        $(".search_prompt").show();
    }).one('focusout', function () {
        $(".search_prompt").hide();
    });
});
</script>

http://api.jquery.com/one/

Upvotes: 3

Related Questions