jQuery Tutorial Tutorials - jQuery.cssHooks

jQuery jQuery.cssHooks object

The jQuery.cssHooks object in jQuery is used to pre-process for normalizing CSS property naming before you setting and getting particular CSS value.

For example:
when we write css code,we have to define all properties for different browsers.

.testClass{
    -webkit-transform: translateY(20px);
    -moz-transform: translateY(20px);
    -ms-transform: translateY(20px);
    -o-transform: translateY(20px);
    transform: translateY(20px);
}

when we want to add them though jQuery.css() method.
We have to do like this:

$.css({'-webkit-transform':'translateY(20px)','-moz-transform':'translateY(20px)','-ms-transform':'translateY(20px)','-o-transform':'translateY(20px)','transform':'translateY(20px)'})

A css hook can let .css() method accept the standard property nametransform,normalize theses vendor-prefixed CSS property naming.

$.css('transform':'translateY(20px)');

jQuery jQuery.cssHooks Template

(function( $ ) {
 
// First, check to see if cssHooks are supported
if ( !$.cssHooks ) {
  // If not, output an error message
  throw( new Error( "jQuery 1.4.3 or above is required for this plugin to work" ) );
}
 
// Wrap in a document ready call, because jQuery writes
// cssHooks at this time and will blow away your functions
// if they exist.
$(function () {
  $.cssHooks[ "someCSSProp" ] = {
    get: function( elem, computed, extra ) {
      // Handle getting the CSS property
    },
    set: function( elem, value ) {
      // Handle setting the CSS value
    }
  };
});
 
})( jQuery );

jQuery jQuery.cssHooks Example

example1

To make it easier to understand, we will show you a special example:

  1. create our custom property lautturi
  2. add a class when user set the lautturi property actually.
$.cssHooks.lautturi = {
    set: function( elem, value) {
        elem.className = value;
    }
};
...
...
$(function () {
    $( "#test" ).css( "lautturi", "classLautturi" );
});

Try it

example2

  1. check to see if cssHooks are supported
  2. determine whether the browser supports the standard property
  3. use $.cssHooks to normalize a vendor-specific CSS property
(function( $ ) {
// First, check to see if cssHooks are supported
if ( !$.cssHooks ) {
  // If not, output an error message
  throw( new Error( "jQuery 1.4.3+ is needed for this plugin to work" ) );
}
 
function styleSupport( prop ) {
  var vendorProp, supportedProp,

    // Capitalize first character of the prop to test vendor prefix
    capProp = prop.charAt( 0 ).toUpperCase() + prop.slice( 1 ),
    prefixes = [ "Moz", "Webkit", "ms" , "o"],
    div = document.createElement( "div" );

  if ( prop in div.style ) {
    // Browser supports standard CSS property name
    supportedProp = prop;
  } else {
    // Otherwise test support for vendor-prefixed property names
    for ( var i = 0; i < prefixes.length; i++ ) {
      vendorProp = prefixes[ i ] + capProp;
      if ( vendorProp in div.style ) {
        supportedProp = vendorProp;
        break;
      }
    }
  }
 
  div = null;
  $.support[ prop ] = supportedProp;
  return supportedProp;
}

$(function () {
    var transform = styleSupport( "transform" );
    
    // Set cssHooks only for browsers that support a vendor-prefixed border radius
    if ( transform && transform !== "transform" ) {
        $.cssHooks.transform = {
            get: function( elem, computed, extra ) {
                return $.css( elem, transform );
            },
            set: function( elem, value) {
                elem.style[ transform ] = value;
            }
        };
    }
});
 
})( jQuery );

$(function () {
    $( "#test" ).css( "transform", "translateY(20px)" );
});

Try it

jQuery jQuery.cssHooks Practical occasion

Inside jQuery, as you can see, it use cssHooks to deal with box-sizing: border-box; or box-sizing: content-box;

Refer to jQuery .css() method Notice for more information.

// jQuery 3.4.1 line 6767
jQuery.each( [ "height", "width" ], function( i, dimension ) {
	jQuery.cssHooks[ dimension ] = {
		get: function( elem, computed, extra ) {
			if ( computed ) {

				// Certain elements can have dimension info if we invisibly show them
				// but it must have a current display style that would benefit
				return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&

					// Support: Safari 8+
					// Table columns in Safari have non-zero offsetWidth & zero
					// getBoundingClientRect().width unless display is changed.
					// Support: IE <=11 only
					// Running getBoundingClientRect on a disconnected node
					// in IE throws an error.
					( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
						swap( elem, cssShow, function() {
							return getWidthOrHeight( elem, dimension, extra );
						} ) :
						getWidthOrHeight( elem, dimension, extra );
			}
		},

		set: function( elem, value, extra ) {
			var matches,
				styles = getStyles( elem ),

				// Only read styles.position if the test has a chance to fail
				// to avoid forcing a reflow.
				scrollboxSizeBuggy = !support.scrollboxSize() &&
					styles.position === "absolute",

				// To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991)
				boxSizingNeeded = scrollboxSizeBuggy || extra,
				isBorderBox = boxSizingNeeded &&
					jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
				subtract = extra ?
					boxModelAdjustment(
						elem,
						dimension,
						extra,
						isBorderBox,
						styles
					) :
					0;

			// Account for unreliable border-box dimensions by comparing offset* to computed and
			// faking a content-box to get border and padding (gh-3699)
			if ( isBorderBox && scrollboxSizeBuggy ) {
				subtract -= Math.ceil(
					elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -
					parseFloat( styles[ dimension ] ) -
					boxModelAdjustment( elem, dimension, "border", false, styles ) -
					0.5
				);
			}

			// Convert to pixels if value adjustment is needed
			if ( subtract && ( matches = rcssNum.exec( value ) ) &&
				( matches[ 3 ] || "px" ) !== "px" ) {

				elem.style[ dimension ] = value;
				value = jQuery.css( elem, dimension );
			}

			return setPositiveNumber( elem, value, subtract );
		}
	};
} );
Date:2019-08-19 16:23:34 From:www.Lautturi.com author:Lautturi