Given a current CMS we are working in, I need to call functions within a custom data-attribute. Is it possible to call the contents of a data attribute as a function to run like below? Simple example:
Set
<button data-function="alert('hello world')">Run Function</button>
Run
$('button').attr('function');
I believe the above is just getting the contents and not actually executing anything when written.
Is this possible?
You could create a Function from the data attribute:
// create
var funcStr = $('button').data('function');
var f = new Function(funcStr);
// invoke
f();
See MDN
This is another approach if the function is known.
$(document).ready(function() {
$('button').click(function() {
var functionObject = JSON.parse($('button').attr('data-function'));
window[functionObject.name].apply(window, functionObject.arguments);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button data-function='{"name": "alert", "arguments" : ["hello world"]}'>Run Function</button>
It parses the JSON string from the data-function attribute. Call the function provided by name using the window object (eliminating eval) and passes the arguments (inside an array) to the function using apply.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With