CSS Hooks in JQuery

Introduction
 
Based on JQuery API documentation, the CSS hooks are used to define custom properties or normalize CSS property naming. In this blog, we are going to see how to normalize CSS property naming with a simple code snippet as an example.
 
CSS Hooks in JQuery
 
CSS Hooks contains get and set functions. The get function is used to handle, getting the CSS Property, and the set function is used to handle, setting the CSS value.
 
CSSHook.html
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>  
  5. <meta charset=utf-8 />  
  6. <title>CSS Hooks</title>  
  7. </head>  
  8. <body>  
  9.   <div>hello world</div>  
  10.   <label id='lblgetproperty'></label>  
  11.   <script>  
  12.   (function($) {    
  13.   var directions = ["Top""Right""Bottom""Left"];  
  14.   $.cssHooks.border = {  
  15.     get: function(elem, computed, extra) {  
  16.       var res = [];  
  17.       $.each(directions, function(i, dir) {  
  18.         res.push($.css(elem, "border" + dir));  
  19.       });  
  20.       return res.join("-");  
  21.        
  22.     },  
  23.     set: function(elem, value) {  
  24.       $.each(value.split("-"), function(i, val) {  
  25.         elem.style["border" + directions[i]] = val;  
  26.       });  
  27.     }  
  28.   };  
  29.   
  30. })(jQuery);  
  31.   
  32. $(function() {  
  33.   $("div").css("border""1px Solid-1px solid-1px solid-1px solid");        
  34.    $("#lblgetproperty").text($("div").css("border"));  
  35. });  
  36.   </script>  
  37. </body>  
  38. </html>  
 
From the above code, you can observe the set method has two parameters. The first parameter is used to set the CSS property and the second one is used to set the value for the property. In my case the value is the string ("1px Solid-1px solid-1px solid-1px solid") which will be split at a hyphen(‘-’) and looped.
 
Get method is opposite to set, getting each value and join them as a string, so the loop in get method will pull out CSS setting using $.css method and add them to an array then finally it returns as a string by joining. 
 
 Run the HTML file in the browser:
 
 
 
From the above figure, you can see the border is applied to the div, which contains the text Hello Word and, in the label, it will display the value given to the property.
 
Reference
 
 
Summary
 
So far, we have seen what are CSS Hooks and how they are used to define the custom CSS properties. Will see more about this in my upcoming blogs.
Next Recommended Reading Create Dynamic Tabs Using Jquery And CSS