anwartheravian anwartheravian - 3 months ago 9
AngularJS Question

Angular Watch on element show not working

I'm using an agular

to trigger an alert when the element become visible.

var scrollElement = "#hiddenObj";
$scope.$watch(function() { return $(scrollElement).is(':visible') }, function() {

Problem is that the alert is shown on page load though on page load, the element is hidden by default, and is shown only on click of some link.

Just to confirm my assumption, I put a break point just before this code, and in my console, I executed this code:


and it return
. That confirmed the element is invisible on page load. I don't know why the alert is still displayed on page load. And when I click the link, and
actually becomes visible, nothing happens.

Is there anything I'm missing here?


The watch listener callback will be executed whenever the watchExpression changes, not when it's true/false. So, when your page is loaded your watchExpression value will be false and the listener will be executed. To avoid that, you can check for the new value of your watchExpression:

$scope.$watch(function() { return $(scrollElement).is(':visible') }, function(newVal) {
     if(newVal === true) {

        alert('Element showed');

The second problem is that the watchExpression is called on every call to $digest(). So, your click handler (to show/hide the element) must trigger a $digest cycle in order to evaluate the expression, ng-click will be a good idea.

In your case the watchExpression is:

function() { return $(scrollElement).is(':visible') }