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
-
Can you make a jsFiddle?David G– David G2013年02月03日 13:48:47 +00:00Commented Feb 3, 2013 at 13:48
2 Answers 2
<script>
$(function() {
$(".search_prompt").hide();
$("#text").one('focusin', function() {
$(".search_prompt").show();
}).one('focusout', function () {
$(".search_prompt").hide();
});
});
</script>
answered Feb 3, 2013 at 13:48
salexch
2,7041 gold badge21 silver badges17 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
bikeshedder
7,5471 gold badge28 silver badges30 bronze badges
Comments
lang-js