In my application, there is a messaging custom element.
I want to send a certain notification to a user only in case that element is not visible at the moment (or out of the viewport).
How could that be done with Polymer?
In my application, there is a messaging custom element.
I want to send a certain notification to a user only in case that element is not visible at the moment (or out of the viewport).
How could that be done with Polymer?
You could use Element.getBoundingClientRect()
to test whether an element is visible in the viewport (see How to tell if a DOM element is visible in the current viewport?):
Polymer({
...
_onSomeEvent: function() {
var targetEl = /* ... */;
if (!this._isElementInViewport(targetEl)) {
// send notification to user
}
},
_isElementInViewport: function(el) {
const rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
});
Based on your other question, I'm assuming you're asking in the context of <iron-list>
. If, for example, you'd like to determine the viewport-visibility of a specific list item, you could test whether the item's index is between <iron-list>.firstVisibleIndex
and <iron-list>.lastVisibleIndex
.
Polymer({
...
_onSomeEvent: function() {
var targetEl = /* ... */;
if (!this._isElementInViewport(targetEl)) {
// send notification to user
}
},
_isElementInViewport: function(el) {
var index = /* get index of el */;
return index >= this.$.myIronList.firstVisibleIndex &&
index <= this.$.myIronList.lastVisibleIndex;
}
});