views:

28

answers:

2

Hi,

I'm trying to write a simple placeholder jQuery plugin for a site of mine but of course I only want to fire the function if the native placeholder attribute isn't supported…

How can I test for native support of the placeholder attribute?

Thanks for stopping by.

+1  A: 

Use the Modernizr library, which you can find here: http://www.modernizr.com/

And then do this:

if (Modernizr.input.placeholder) {
  // your placeholder text should already be visible!
} else {
  // no placeholder support :(
  // fall back to a scripted solution
}

Modernizr is really handy for testing the browser's support for almost all HTML5 functionality.

Ender
Thanks for your answer. I am already using Modernizr in my document however for this plugin to work on all sites I don't want to rely on any external libraries such as Modernizr other than jQuery of course. On my current page that I am building this indeed works great, but just for general compatibility I'd prefer something not reliant on Modernizr.
Jannis
+3  A: 

You can add to $.support quite easily by inserting this at the top of the Javascript you've written:

jQuery.support.placeholder = (function(){
    var i = document.createElement('input');
    return 'placeholder' in i;
})();

You can then use either $.support.placeholder or jQuery.support.placeholder anywhere in your code.

NB This code adapted from diveintohtml5, the link provided by hellvinz above.

lonesomeday
This is brilliant and exactly what I was looking for. Thank you. PS: Thanks for the link, great resource. *Bookmarked!*
Jannis
Thank hellvinz, not me, for the link! What's more, it would be trivial to create a plugin that imports all Modernizr tests to `$.support`. A quick test reveals that it would be a 11kb file once minified.
lonesomeday
even if all i want to test for is form functionality?
Jannis
No, that's for the whole library. I've rewritten the diveintohtml5.org HTML5 form code as a plugin to extend `$.support`. It's at http://pastebin.com/NVs09xzX at the moment and I'll put it on the jQuery site as a plugin soon.
lonesomeday
Hey, thanks for your comment! That little plugin is exactly what I needed. Do you mind if I include it in my jquery plugin that I'm writing at the moment?
Jannis