12

Is it possible to write an html attribute that will store the name of a javascript function and then extract that val() and execute that function? Example:

<button id="example" data-function-name="showAllElements()">

and then in js/jq

fn = $('#example').data('function-name');

fn;
2
  • 3
    To find out, you have to try it :) Commented Dec 12, 2014 at 16:20
  • That may help you : stackoverflow.com/a/26020014/2324107. It is used for variable, but it is the same way with functions. Commented Dec 12, 2014 at 16:26

3 Answers 3

26

You can, yes. Whether you should is another question entirely, to which the answer is almost certainly "no" (in terms of executing the string; in terms of the alternative shown below, there are times it's useful).

The way you'd evaluate that snippet of code (what you have isn't just a function name, because of the ()) would be to use the dreaded eval:

eval(fn);

There's almost always a better option than using eval. (See below.)

eval example:

$("#example").on("click", function() {
  var fn = $("#example").attr("data-function-name");
  eval(fn);
});

function showAllElements() {
  alert("showAllElements was called");
}
<button type="button" id="example" data-function-name="showAllElements()">Click Me</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


One of the better options is to store your function references as properties on an object, and then use brackets notation to get the function reference based on the function name:

Example:

var functions = {
  showAllElements: function() {
    alert("showAllElements was called");
  }
};

$("#example").on("click", function() {
  var fn = $("#example").attr("data-function-name");
  functions[fn]();
});
<button type="button" id="example" data-function-name="showAllElements">Click Me</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Note that there, I'm just storing the function name, not arbitrary code.

Update: See canon's answer for a clever way to handle it if you have your functions nested inside an object, e.g. mumble.foo.doSomething, using reduce. (reduce is an ES5 feature, but it's polyfillable.)


Side note: Unless you're doing something more than just retrieving the value of a data-* attribute, don't use data, use attr. data initializes a data cache for the element, reads in all of the data-* attributes for that element, and copies them to cache. If you're not using it, there's no reason to do that. The idea that you use data to access data-* attributes is a common misconception.

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

3 Comments

Thanks I really like your suggestions! Also, could you explain to me a situation where you would use .data()?
I was, sadly, misusing jQuery's data() for a while... thinking it was a wrapper/polyfill for dataset.
@canon: You and a lot of other people. :-) I keep thinking how, in some alternate universe, the API could have made that more clear, because people get misled by it. But I haven't come up with anything, and the cat's out of the bag now anyway...
13

Sure... assuming that showAllElements is global...

function showAllElements() {
  console.log("test!");
}
document.querySelector("button").addEventListener("click", function(e) {
  var functionName = this.getAttribute("data-function-name");
  window[functionName]();
});
<button id="example" data-function-name="showAllElements">x</button>

Now, let's say your attribute is actually something harrier, like: foo.bar.showAllElements...

var foo = {
  bar: {
    showAllElements: function() {
      console.log("test!");
    }
  }
};

document.querySelector("button").addEventListener("click", function(e){
    var functionName = this.getAttribute("data-function-name");
    // Split by "." and resolve each segment starting at the window. Invoke with ()
    functionName.split(".").reduce((o,n) => o[n], window)();
});
<button id="example" data-function-name="foo.bar.showAllElements">x</button>

7 Comments

Nice, didn't think of that!
Only works for global functions, of course, and global functions, like all globals, are a Bad Idea.
@T.J.Crowder - No, it would work for any object as long as you have a reference to it. It's just looking up a function by it's name and then calling it. Nothing magic about that. Could just as easily be: ({ foo: function(){ console.log('bar'); } })['foo']();. No global functions there.
I realized I'd left it out as a hit Post. Didn't see any other answers. Yours may well have been there, but that's not why I added it. I just realized I'd committed the sin of telling the OP how to do it with eval, telling them they probably shouldn't, and not giving them the alternative! :-)
Ooooh, +1 for the clever use of reduce!
|
0

While I don't think you can do it this way with an HTML attribute directly (except with global functions as mentiopned above), if you can add the data element with javascript at page load you can do it directly. As said here, jquery's $.data() is not the same as the data-* attributes. According to the jQuery docs, the value stored using .data() "The new data value; this can be any Javascript type except undefined."

So you can store a function directly using

function my_func(){
   // Do stuff
}
$(function(){
   $('#foo').data('func', my_func);
});

And then later

var func = $('#foo').data('func');
if( $.isFunction( func ) ) {
   func.call( $('#foo'), somearg );
}

I have an example as a fiddle.

This has the advantage that you can have the functions in enclosures, etc. as long as you add them to the elements within the same enclosure scope.

Comments

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.