Pushing Detector Data to the Browser Tutorial
While it's great to have information on the server to act on what if you want to access the data in the browser to manipulate CSS or JavaScript in the same way as you'd do with Modernizr? Detector offers two helpers that address these needs, DetectorHelpers::createHTMLList()
and DetectorHelpers::createJavaScriptObj()
.
As of Detector 0.7 this feature is no longer included when including the base Detector library. To enable it you must include a separate file. To get this to work include following at the beginning of your script:
require_once("path/to/Detector/Detector.php");
require_once("path/to/Detector/lib/helpers/detectorHelper.php");
Detector can add classes based on features in much the same way that Modernizr does. This allows developers to modify CSS rules based on the availability of certain features. To add the classes include the following code in your HTML tag:
class="<?=DetectorHelpers::createHTMLList($ua)?>"
This will list every feature that Detector supports. In order to limit the class list to a select set of options include a comma-delimited list of features:
class="<?=DetectorHelpers::createHTMLList($ua,"geolocation,cssanimations,cssgradients")?>"
To include the os
, osFull
, browserFull
, device
, and deviceFull
user-agent properties from ua-parser-php do the following:
class="<?=DetectorHelpers::createHTMLList($ua,"geolocation,cssanimations,cssgradients",true)?>"
There is a simple demo that uses the last example that you can view.
Detector can create a JavaScript object of values based on the features the current user-agent supports. This object can be used in the same way that the Modernizr object works. These means that you can still use resource loaders like YepNope. To create the object simply include the following in the <head>
portion of your HTML code:
<?=DetectorHelpers::createJavaScriptObj($ua)?>
This will list every feature that Detector supports. In order to limit the class list to a select set of options include a comma-delimited list of features:
<?=DetectorHelpers::createJavaScriptObj($ua,"browserFull,isMobile,geolocation,cssanimations,cssgradients")?>
You can include all of the features captured by ua-parser-php.
In your JavaScript you can access the Detector object in the same way you'd access the Modernizr object. For example:
Detector.geolocation
There is a simple demo that uses the last example that you can view.