I am working on adding "search" text to a search box. I am trying to achieve:
onfocus: disappear text
And
onblur: reappear text
So far I have achieved this but i have had to hardcode it into html:
eg.
<input type="text" name="s" id="search-text" size="15" value="Search"
onfocus="if (this.value==this.defaultValue)
this.value='';" onblur="if(this.value==''){this.value='Search'}">
And if I add this the of my .html file I am getting the same result:
eg.
<script type="text/javascript">
var defaultText = "Search...";
var searchBox = document.getElementById("search");
//default text after load
searchBox.value = defaultText;
//on focus behaviour
searchBox.onfocus = function() {
if (this.value == defaultText) {//clear text field
this.value = '';
}
}
//on blur behaviour
searchBox.onblur = function() {
if (this.value == "") {//restore default text
this.value = defaultText;
}
}
</script>
(courtesy: http://zenverse.net/javascript-search-box-show-default-text-on-load/)
What i am trying to achieve is using the above code in an external .js file but no matter what I do i cannot manage to back-link the code to my search box in my .html file.
I am sorry if this is a bad question I have made about 10 different .html and .js files swapping and remapping code and still can't get it to work without having the javascript in the actual .html file.
Any help would be much appreciated Thank You.
Use the HTML5 placeholder attribute:
<input type="text" placeholder="Search" />
Notice that the text doesn't go away until the user enters some text. This way, the user will see the hint for longer.