Placeholder Text Support for crap browsers


/ Published in: JavaScript
Save to your folder(s)

This function emulates support for placeholder text on form elements, run it inside a loop or call it by passing in a specific id reference


Copy this code and paste it in your HTML
  1. $('document').ready(function(){
  2. $('input').each(function(count,element){
  3. if( $( element ).attr('placeholder') ){
  4. search_text(element);
  5. }
  6. });
  7. });
  8.  
  9.  
  10. function search_text(e)
  11. {
  12. // Function to detect placeholder support where Modernizr isnt available
  13. var supports_placeholder = function()
  14. {
  15. var i = document.createElement('input');
  16. return 'placeholder' in i;
  17. }
  18.  
  19. // Check jQuery is available
  20. if( typeof( $ ) != 'function' )
  21. return false;
  22.  
  23. // Check for placeholder support
  24. if( typeof( Modernizr ) != 'object' && supports_placeholder() == false ){
  25. return false;
  26. }else if( Modernizr.input.placeholder ){
  27. return false;
  28. }
  29.  
  30. // Check if an object is passed directly (like from an each loop), or by an ID reference
  31. var input = false;
  32. if( typeof(e) == 'object' ){
  33. // whole object passed
  34. input = e;
  35. }else{
  36. // reference to object passed
  37. input = document.getElementById(e);
  38. }
  39.  
  40. if( input ){
  41.  
  42. var search_advice_text = $(input).attr('placeholder');
  43.  
  44. if( $(input).val().length == 0 ){
  45. $(input).val( search_advice_text ).css({'color':'#ccc'});
  46. }
  47. $(input).focus(function(){
  48. if( $(this).val().length == 0 || $(this).val() == search_advice_text ){
  49. $(this).val( '' ).css({'color':'#444'});
  50. }
  51. }).blur(function(){
  52. if( $(this).val().length == 0 ){
  53. $(this).val( search_advice_text ).css({'color':'#ccc'});
  54. }
  55. });
  56. }
  57.  
  58. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.