0

I defined a function to change the elements attribute.
I want to pass an argument to this function in 'addEventListener' and this is my problem.

Here is the function :

function collapse (el) {
    var _cl = el.classList;
    _cl.add("box_size1");
    el.removeAttribute("id");
}

Here is main code :

window.onload = function() {
    var el = document.getElementById("box_size2");
    el.addEventListener("click", collapse(???));
}

what shall I write instead of question marks ?

abagshaw
  • 6,162
  • 4
  • 38
  • 76
  • https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_value_of_this_within_the_handler – Phil Jul 12 '17 at 05:27
  • Possible duplicate of [How to pass parameter to function using in addEventListener?](https://stackoverflow.com/questions/12024483/how-to-pass-parameter-to-function-using-in-addeventlistener) – Sebastian Simon Jul 12 '17 at 05:27
  • Have you searched “JavaScript how to pass arguments to addEventListener” in Google? – Sebastian Simon Jul 12 '17 at 05:28

1 Answers1

2

No need pass anything with function.Default this is bind in the function .Just call this inside the function instead of el

window.onload = function() {
var el = document.getElementById("box_size2");
el.addEventListener("click", collapse);
}

function collapse() {
var _cl = this.classList;
_cl.add("box_size1");
this.removeAttribute("id");
console.log(this.outerHTML)
}
<button id="box_size2">click</button>
prasanth
  • 22,145
  • 4
  • 29
  • 53