0

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>
salexch
2,7041 gold badge21 silver badges17 bronze badges
asked Feb 3, 2013 at 13:45
1
  • Can you make a jsFiddle? Commented Feb 3, 2013 at 13:48

2 Answers 2

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

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

answered Feb 3, 2013 at 13:48
Sign up to request clarification or add additional context in comments.

Comments

0

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? :-)

answered Feb 3, 2013 at 13:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.