0

I have this code for collapsible items.

var coll = document.getElementsByClassName("collapsible");

for (var i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function() {        
        this.classList.toggle("active");
        var p = this.nextElementSibling;
        if (p.style.maxHeight){
            p.style.maxHeight = null;
        } else {
            p.style.maxHeight = p.scrollHeight + "px";
        } 
    });
    if (window.screen.availWidth >= 768) coll[i].onclick.apply(coll[i]);
}

The last line is meant to automatically expand all collapsibles on larger screens. But it gives me an error:

Uncaught TypeError: Cannot read property 'apply' of null

How can I fix this?

CaptainCodeman
  • 1,951
  • 2
  • 20
  • 33
  • 1
    My guess is that coll[i].onclick is not defined. You defined an event listener, which is different. –  Nov 29 '20 at 00:03
  • 1
    firstly, `document.addEventListener` is NOT `document.onEvent`.. they are two separate things.. adding an event listener can be applied and onevent will still be null – The Bomb Squad Nov 29 '20 at 00:07

1 Answers1

1

coll[i].onclick is null, onclick is an event not a function, so you would like to use click function there.

Not sure what are you trying to achieve by passing coll[i] as this for click function. but try:

coll[i].click.apply()

or simpler:

coll[i].click()
toHo
  • 398
  • 5
  • 28
  • 1
    Thanks, this worked. The old code was something I saw on here: https://stackoverflow.com/questions/906486/how-can-i-programmatically-invoke-an-onclick-event-from-a-anchor-tag-while-kee – CaptainCodeman Nov 29 '20 at 14:06