Nikita Ivanov
Nikita Ivanov

Reputation: 31

Uncaught TypeError: Cannot read property 'target' of undefined

I want to create tabs on pure js and decided to implement it through "data-attr".

var allTabs = document.querySelectorAll('.tab'); //all tabs on page

var clickTabHandler = function (event) {

    var target = event.target;

    var id = target.getAttribute('data-content');

    alert(id);

};

for (var i = 0; i < allTabs.length; i++) {
    allTabs[i].onclick = clickTabHandler(event);
}

in the console get : Uncaught TypeError: Cannot read property 'target' of undefined;

Why?

Upvotes: 3

Views: 11524

Answers (1)

gurvinder372
gurvinder372

Reputation: 68393

replace this line

allTabs[i].onclick = clickTabHandler(event);

by

allTabs[i].onclick = clickTabHandler;

since this and event will be passed to it implicity

Upvotes: 3

Related Questions