Lets execute some evals from data attributes!!

January 19, 2013

Ok so in making a super cool piece of code I came across a problem. I wanted to pull some functions from the data attributes on some elements.

This could be for any reason. Lets pretend you have some functions you need to be able to execute after page load, depending on what the user clicks.

The  first step is to make your functions and we will embed them in our elements using the data attribute that Andy Stramer talked to you about in the post HTML data attributes with jQuery.

do it in this way


<div class="whateverclassyouwant" data-function="function(){insertanyfunctionhere}" > </div>




So what this does is stores an entire function as a string inside the elements you might be passing from the server.

Now what we do is some awesome javascript and jQuery:


function executeThisOnElementClick(){
        var method = $(this).data('function');
	eval('var execute = '+method);
        execute();
}

This is a simple yet easy way to execute functions on element click, that you might need to receive from the elements themselves.

My NEXT post will have great example of this.

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive