10

Is it possible passing a function with a custom data attribute?

This does not work:

<div data-myattr="hello();">
</div>
function hello(){
    console.log('hello');
}

When I get the attribute it's a string with the value "hello();" instead of the function. How to solve this?

4
  • Which technology are you using? PHP/jquery? Or is it a javascript only question? Commented Jan 3, 2013 at 15:29
  • how you want use that attribute? Commented Jan 3, 2013 at 15:29
  • no, this way sure will not work. but according to your purpose you can use whatever you like. e.g. onblur, onclick, etc... what do you need exactly Commented Jan 3, 2013 at 15:31
  • I'm using Javascript. Creating my own components using Mozilla x-tag, which is Javacript. Commented Jan 3, 2013 at 15:44

4 Answers 4

18

You could do it as follows:

<div data-myattr="hello"></div>
function hello(){
    console.log('hello');
}

function executeFunctionFromData(){
    var d = 'hello' // Save `data-myattr` to d; (Obviously, this is just a hardcoded value as an example)
    window[d](); // Execute the function.
}

This works because the function hello is defined in the global scope, and as such, is a property of the window object.

Sign up to request clarification or add additional context in comments.

1 Comment

Good solution - alternatives such as using "eval" give me the chills.
5
<div id='some' data-my-function="function(x){console.log(x);}"></div>

js:

var myfunction = $('#some').data('my-function');

if(myfunction != undefined){     
    eval("myfunction = "+myfunction, myfunction);    
}

if(typeof myfunction ==="function") {
    myfunction('Cristo Rabani!');
}

Comments

1

Using Webpack.

<div data-func="funcName"></div>
window.funcName = function() {};

Comments

-2

Use eval:

eval("alert('hello');");

Will show hello;

2 Comments

That is silly. If eval works, callling the function by hello(); works too.
Silly? Could you explain why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.