Jump to content

Javascript do something only once


joe92

Recommended Posts

I need to create a javascript function which will only do something once. For example, there is a text box with preset text in it. Onfocus wipes that content so that the user can type their own in. However, I need it to only wipe the content once so I need that onfocus to be disabled after the first time. Is there a way of doing this all in javascript?

 

Is there a way of changing the javascript function using javascript? So that onfocus I could have something at the end of the function which then changes the onfocus event to something else.

 

Cheers

Joe

Link to comment
https://forums.phpfreaks.com/topic/243090-javascript-do-something-only-once/
Share on other sites

You can easily make a JavaScript function overwrite itself:

 

var foo = function() {
  alert('say foo');
  foo = function() {
    alert('never again say foo');
  }
}
foo();
foo();
foo();

 

The first time you call foo() it will display 'say foo', every other call after that will display 'never again say foo'.

If you remove the function or only allow it to work one time, you would need to create a function for each input field (which defeats the purpose of a function). You can do something like this instead (notice the title is the same as the default value)

<input type="text" value="Default Value" title="Default Value" onfocus="if (this.value == this.title) this.value = '';" onblur="if (this.value == '') this.value = this.title;" />

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.