Home > OS >  DOM element dataset contains call with (this) parameter
DOM element dataset contains call with (this) parameter

Time:09-21

I am trying to send (this) as parameter to event listener that will dynamically create function contained dataset.

my document.listener has other element not just this one.

document.addEventListener('click', function(event) {
    let el = event.target;
    if (el.hasAttribute('data-todo') ) {
        let FN = new Function( el.dataset.todo );
        FN();
    }
    
});

function toggleDisable(el) {
  console.log( el.tagName );
  el.classList.add('disabled');
}
<div class="wrapper">
    <button type="button" data-todo="toggleDisable(this)">Diable me</button>
</div>

CodePudding user response:

Since you're evaluating it inside the click event listener, use event.target to reference the element itself instead:

document.addEventListener('click', function(event) {
    let el = event.target;
    if (el.hasAttribute('data-todo') ) {
        let FN = new Function( el.dataset.todo );
        FN.this = event.target;
        FN();
    }
    
});

function toggleDisable(el) {
  console.log( el.tagName );
  el.classList.add('disabled');
}
<div class="wrapper">
    <button type="button" data-todo="toggleDisable(event.target)">Diable me</button>
</div>

  • Related