Site Mod: Search Text with jQuery

I added a very simple mod today that you might have noticed – there is now some text added dynamically to the search box that should give a better indication as to what that area is for.

I used jQuery for this, just to further increase my exposure to the library, and I must say that it was extremely easy. I love the way you can simply attach functions to events with jQuery: you can see that when the search box has focus the "Search…" phrase disappears, allowing you to type straight away without having to worry about it.

After including the jQuery library, the code needed for this is:

</p> <pre> $(document).ready(function() { $("#searchbox").val("Search..."); search_flag = false; $("#searchbox").focus(function() { if(search_flag != true) { $("#searchbox").val(""); search_flag = true; } }); }); </pre> <p>

Originally, I had attached the function to the click event, rather than the focus event. I realised that this was probably bad practice (since it doesn't account for keyboard events) so I corrected it. I'm looking into ways to make the code even more compact too, perhaps by removing the need for search_flag if such a thing is possible.

If you're planning on trying out jQuery then I highly recommend bookmarking Visual jQuery. That site is an invaluable reference during development. I wouldn't have found the focus event otherwise!

Just from this I'm looking forward to seeing what else I can do with JavaScript and jQuery. :)