Emulating jQuery :visible selector with plain Javascript

8.1k views Asked by At

I am converting a piece of code from jQuery to ChocolateChip UI, and this piece of code is stumping me as ChocolateChip UI doesn't support ':visible' for its implementation of is()

if (interactive && block.is(':visible')) {
            block.fadeOut(250, function() {
                block.html(newContent);
                block.fadeIn(750);
            });
            showHighlight($("#character_text"));
} 

The error I get is:

Uncaught SyntaxError: Failed to execute query: ':visible' is not a valid selector. 

Two questions:

  1. How can I emulate is(':visible') using plain JavaScript?
  2. How can I extend ChocolateChip UI's is() to handle :visible?
2

There are 2 answers

0
LeGEC On BEST ANSWER

As an answer to your second question :

ChocolateChip UI does not seem to offer a way to extend selectors. The code for the .is() function shows that, when the selector is a string, this string is directly fed to .querySelectorAll().

However, you can also pass a function as an argument, so using the predicate Pieter de Bie pointed out, you can write :

$.fn.extend({
   isVisible: function(){
       return this.is( function(elem){
           return elem.offsetWidth > 0 || elem.offsetHeight > 0;
       });
   }
});

if ( $('.mySelector').isVisible() ){
    ....
}

Another solution is to use jQuery : the authors stipulate that their library should be compatible with jQuery > 2.0.3 (see the project's Readme).

1
Pieter De Bie On

As an answer on your first question:

In jQuery 1.3.2 an element is visible if its browser-reported offsetWidth or offsetHeight is greater than 0. (source)

So

$(element).is(":visible")

Should be the same as

(element.offsetWidth > 0 || element.offsetHeight > 0)