Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a callback function as a html data attribute

Tags:

javascript

I have created a DOM structure like this

<div data-execute="someFunction.abc" id="someId">
  </div>

I am able to retrive the attribute in js but I intend to execute this as a callback function. So I am doing like this

var x = document.getElementById("someId").getAttribute('data-execute');

As expected this is returning someFunction.abc .But on consoling typeof(x) it is showing "string".Please refer to this fiddle

var someFunction = function() {
  alert("Hello")
}
var load = (function(module, global) {
  var x = document.getElementById("someId").getAttribute('data-execute');
  console.log(typeof(x))

}(load || {}, this))
<div data-execute="someFunction.abc" id="someId">
  Some Function
</div>

I also checked this link Passing a Javascript function through inline data- attributes

But no way I am able to execute it as a call back function.Any help will be truly appreciable.

like image 393
brk Avatar asked Oct 14 '25 11:10

brk


1 Answers

Try this:

<div data-execute="someFunction.abc" id="someId"></div>

var x = document.getElementById("someId").getAttribute('data-execute');
window[x].call();
like image 117
slash197 Avatar answered Oct 17 '25 03:10

slash197