Jump to content

jQuery - determine if element has a background set

jquery javascript css html

  • Please log in to reply
3 replies to this topic

#1 Guest_ElatedOwl_*

Guest_ElatedOwl_*
  • Guests

Posted 08 November 2012 - 10:00 AM

As per my question here, I was looking for a way to check if an element has a background set. (whether it be color or image) The default blank value differs between browsers. Chrome v22, for example, returns the following
background: rgba(0, 0, 0, 0) none repeat scroll 0% 0% / auto padding-box border-box
background-color: rgba(0, 0, 0, 0)
background-image: none
while IE8 returns
background: undefined
background-color: transparent
background-image: none

So what would seem to be as trivial as just checking background via .css() gets a little more complicated. Thanks to the idea from @pebbl I've made a small jQuery function to determine if an element has a background.

There are two code blocks below, closure and non-closure; if you're redefining $ (ie, $ != jQuery) use the closure version.

Non-closure
$.fn.hasBack = function()
{
	var me = $.fn.hasBack;
	if(!me.cache)
	{
		// get the background color and image transparent/none values
		// create a temporary element
		var $tmpElem = $('<div>').hide().appendTo('body');
		$.fn.hasBack.cache = {
			color: $tmpElem.css('background-color'),
			image: $tmpElem.css('background-image')[/indent]
		};
		$tmpElem.remove();
	}
	var elem = this.eq(0);
	return !(elem.css('background-color') === me.cache.color && elem.css('background-image') === me.cache.image);
}
Closure


Exceptions


This was tested in Chrome v22, Firefox v15, Opera 12.1, IE9, IE9 set to browser modes 9 compat, 9, 8, 7 and quirks mode.
Test case here.

#2 SpleenBeGone

SpleenBeGone

    Deer Leader of the Goriest Revolution

  • Administrators
  • 14,951 posts
  • LocationHouston

Posted 08 November 2012 - 10:05 AM

Now the question is, how can you use this to make something interesting?
nmjUGDL.jpg

#3 Guest_ElatedOwl_*

Guest_ElatedOwl_*
  • Guests

Posted 08 November 2012 - 10:18 AM

Heh, it's to fix a bug in something bigger I'm working on. I'm writing a demo engine (a guided user tutorial thing), and I have a case where elements should stand out and it doesn't.

Working example:
Posted Image

Broken example:
Posted Image

so I needed a way to be able to see if an element didn't have a background I could set the parents background to it.

#4 SpleenBeGone

SpleenBeGone

    Deer Leader of the Goriest Revolution

  • Administrators
  • 14,951 posts
  • LocationHouston

Posted 08 November 2012 - 11:20 AM

Ah, very nifty.
nmjUGDL.jpg





Also tagged with one or more of these keywords: jquery, javascript, css, html