Justin
Justin

Reputation: 887

Binding click event to ie8 $window in angularjs

My initial approach to binding a click event in ie8 for angularjs has been this:

var w = angular.element($window);
w.bind('click', function(){alert('hi')});

But that works in every browser except ie8 of course. So I tried:

function bindEvent() {
        if($window.addEventListener)
            $window.addEventListener('click', alert('Hi'), false);
        else
           $window.attachEvent('onclick', alert('Hi ie8')); 
    }

This works for all browsers but in a weird way. As soon as the page loads I get the alert but when I click around I don't see the alert. So the alert only fires on page load but I am clearly saying 'click' or 'onclick' as you can see.

I've tried some hybred approaches such as sticking the bindEvent function into a $timout and even removing from function definition and just call the if-else block in the angularjs controller.

Even got creative with the .bind function and added a 3rd parameter as 'false' to prevent event bubbling up. I'm at a loss as to how to get a click event bound to the ie8 window object so anytime I click on the page it calls a function. Help!

Upvotes: 0

Views: 522

Answers (1)

Mathew Berg
Mathew Berg

Reputation: 28750

It's because your alert is being fired right away, wrap it in a function:

function bindEvent() {
    if($window.addEventListener){
        $window.addEventListener('click', function(){
            alert('Hi')
        }, false);
    }
    else{
        $window.attachEvent('onclick', function(){
            alert('Hi ie8')
        }); 
    }
}

Upvotes: 1

Related Questions