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:
is(':visible')
using plain JavaScript?is()
to handle :visible
?Answer: Use the jQuery :visible and :hidden Selector That means, elements with visibility: hidden; or opacity: 0; are considered visible, since they still preserve space in the layout.
The :visible selector in jQuery is used to select every element which is currently visible. It works upon the visible elements. The elements that are consuming space in the document are considered visible elements. The height and width of visible elements are larger than 0.
To toggle a div visibility in jQuery, use the toggle() method. It checks the div element for visibility i.e. the show() method if div is hidden. And hide() id the div element is visible. This eventually creates a toggle effect.
version added: 1.0jQuery( ":visible" )Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero. Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout.
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)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With