Latest Entries »

Saturday, January 14, 2012

jQuery check if element has border

Sometimes you need to check if an html element has border for some reason. Normally we can use build in function css() for this purpose. But this approach is quite troublesome to find answer due to some facts: $(element).css('property') function returns window.getComputedStyle(element) . For border we have 4 css-computed rules:

.someClass{
    border: 1px solid black;
    /* is in fact computed in browser as */
    border-top-style: solid;
    border-right-style: solid;
    border-bottom-style: solid;
    border-left-style: solid;
}

To check if element has border we need to write something like this. Code is simple but in fact really ugly.

if ($(element).css('border-top-style') != 'none' && 
        $(element).css('border-right-style') != 'none' &&
        $(element).css('border-bottom-style') != 'none' &&
        $(element).css('border-left-style') != 'none'){
    //Has border
    }

Moreover code above may give you wrong result. Imagine situation when web-developer wrote:

.anotherFancyClass{
    /* only bottom border */
    border-bottom: 1px solid black;
    /* is in fact computed as */
    border-top-style: none;
    border-right-style: none;
    border-bottom-style: solid;
    border-left-style: none;
}

Now javascript if condition fail. You can change condition from AND to OR but it is still UGLY code.

Better solution


To check if element has border we will use another functions:

And here's a code and explaination:


$.fn.hasBorder = function() {
    /* outer contains: dimensions + padding + border */
    /* inner contains: dimensions + padding */
  if ((this.outerWidth() - this.innerWidth() > 0) ||  (this.outerHeight() - this.innerHeight() > 0)){
        return true;
    }
    else{
        return false;
    }
  };
  
  /* Usage */
  if ($('#selector').hasBorder()){
      //With border. Such more sophisticated ain't true?
  }

That's all.

0 comments:

Post a Comment