WP-Mix

A fresh mix of code snippets and tutorials

jQuery check inline CSS property

Working on my WordPress plugin, Dashboard Widgets Suite, I needed a quick function to check a property defined via the inline style attribute on a specific element. Here is an easy, plug-n-play solution that works great.

This function accepts a variable that contains the name of whichever property you want to check. If the property is contained within the style attribute of the specified element, the function returns the value of the property. Otherwise it returns false/undefined.

jQuery.fn.inlineStyle = function(prop) {
	
	/*
	
	var styles = this.attr('style'), value;
	
	styles && styles.split(';').forEach(function(e) {
		
		var style = e.split(':');
		
		if (jQuery.trim(style[0]) === prop) {
			
			value = style[1];
			
		}
		
	});
	
	return value; // returns property value or undefined
	
	*/
	
	return this.prop('style')[jQuery.camelCase(prop)]; // returns property value or empty string
	
};

Usage:

Let’s say that we want to check the width property defined via inline style attribute on an element with class .element:

var width = $('.element').inlineStyle('width');

Then to check the value, we can do this:

if (width) { /* the element includes width property in style attribute */ }

Note: the commented out part of the code contains a backup script for if/when jQuery removes the currently undocumented camelCase() function. Feel free to remove it if you have full confidence in camelCase().

Source

★ Pro Tip:

Digging Into WordPressGA Pro