Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript IE error: 'target' is null or not an object

document.onkeydown = function(event) {
    var tagName = event.target.tagName;
    if (tagName != 'INPUT' && tagName != 'TEXTAREA' && !event.alt && event.control) {

        if (event.ctrlKey && event.keyCode == 37) {
            if (_this.currentPage > 1) {
                window.location.href = _this.baseUrl.replace(/%page%/i, _this.currentPage + 1);
            }
        } else if (event.ctrlKey && event.keyCode == 39) {
            if (_this.currentPage < _this.pagesTotal) {
                window.location.href = _this.baseUrl.replace(/%page%/i, _this.currentPage - 1);
            }
        }
    }
}

This gives me an error only in IE 8:

'target' is null or not an object

for that line var tagName = event.target.tagName;

How to fix that? Error happens when I press Ctrl or arrows button.

like image 471
user1815131 Avatar asked Jan 15 '23 01:01

user1815131


2 Answers

IE does not pass in the event object into the event handler. Instead, they use the global event property of the window object. So for IE, you'd use window.event instead.

It is common practice to test for the supplied argument first. You also have to take into account the fact the IE uses srcElement instead of target. To account for all that, use something similar to this:

document.onkeydown = function(event) {
    event = event || window.event;
    var tagName = (event.target || event.srcElement).tagName;
    // Keep up the good work...
}

This should do the trick.

like image 109
Joseph Silber Avatar answered Jan 27 '23 20:01

Joseph Silber


Do it like this:

event = event || window.event;
var tagName = (event.target || event.srcElement).tagName.toUpperCase();
like image 44
I Hate Lazy Avatar answered Jan 27 '23 20:01

I Hate Lazy