joe92 Posted July 28, 2011 Share Posted July 28, 2011 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 Quote Link to comment https://forums.phpfreaks.com/topic/243090-javascript-do-something-only-once/ Share on other sites More sharing options...
trq Posted July 28, 2011 Share Posted July 28, 2011 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'. Quote Link to comment https://forums.phpfreaks.com/topic/243090-javascript-do-something-only-once/#findComment-1248446 Share on other sites More sharing options...
nogray Posted July 28, 2011 Share Posted July 28, 2011 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;" /> Quote Link to comment https://forums.phpfreaks.com/topic/243090-javascript-do-something-only-once/#findComment-1248755 Share on other sites More sharing options...
joe92 Posted July 29, 2011 Author Share Posted July 29, 2011 Thank you very much nogray, that worked a treat! Quote Link to comment https://forums.phpfreaks.com/topic/243090-javascript-do-something-only-once/#findComment-1248933 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.