5

I have to write a function which will create a HTML code of a tag and this function will also pass a function handler to onclick event of created a tag. Code:

function a(text,functionHandler){
    return '<a href="#" onclick="'+functionHandler+'">'+text+'</a>';
}

//usage
var a1 = a('link',function(){
   alert('test');
});

Passing the function to string doesn't work. So my question is: how to pass a function handle to onclick event and get a HTML code of created a tag?

2
  • function is a reserved keyword, use something else like functionName. Commented Aug 29, 2013 at 12:40
  • Did you try my last update ? Also, you should change the title of your question to be more precise on the fact that you need to return an HTML code that will contain the event functions. Commented Aug 29, 2013 at 17:22

5 Answers 5

4

Your current approach has a couple of problems -

  1. function is a keyword. You cannot use it as a parameter.
  2. The way you are using it, you need function name here. Passing a callback won't help.

Rather than returning your anchor as a string, return it as an element -

function createAnchor(text, clickHandler) {
    var link = document.createElement('a');    // creates an anchor element
    link.href = "#";                           // sets the href
    link.onclick = clickHandler;               // sets the click handler
    link.innerHTML = text;                     // assigns the inner html string

    return link;                               // now return it
}

and then -

var myAnchor = createAnchor('link', function () {
    alert('test');
});

// Add this element wherever you want

See the documentation on createElement and element.

EDIT

If you want to add this anchor element to an existing DOM element as a child, use the appendChild -

var myAnchor = createAnchor('link', function () {
    alert('test');
});

document.getElementById('x').appendChild(myAnchor);

Live JSFiddle.

EDIT 2

If you really want your anchor string, then create the anchor element using the above function, append it as a child to your desired element, and then use innerHTML on the parent. The approach is demonstrated here -

function createAnchorString(parentId, text, clickHandler) {
    var link,
        parent;

    link = createAnchor(text, clickHandler);    // call the previous function
    parent = document.getElementById(parentId);
    parent.appendChild(link);

    return parent.innerHTML;
}

var myAnchorString = createAnchorString('x', 'link', function () {
    alert('test');
});

alert(myAnchorString);

Live Fiddle.

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

5 Comments

jsfiddle.net/dejwid/aswXT and as you can see it doesnt work with unnamed function
Yes, your fiddle works but I need a html code of the created a tag
Your answer is the best one but I still can't mark it as accepted because this solution works on appendChild...
@BjörnRoberg long story, bro ;)
@David: Is that a bad thing?
1

You could try like this :

function a(text, callback)
{
    var obj = document.createElement("a");

    obj.textContent = text;
    obj.onClick = callback;
    return obj.outerHTML;
}

The question is : How will it handle the anonymous function passed as callback argument ?

EDIT This should work now :

function a(text, callback){
    return '<a href="#" onclick="if(!this.fireFunc)this.fireFunc='
            + callback.toString()
            + ';this.fireFunc();">'+text+'</a>';
}

Just using toString() on an anonymous function permits you to get its code.

This is a very hackish way, and doesn't work on named functions (It wouldn't be hard now to make it work).

FIDDLE http://jsfiddle.net/gZ3YD/1/

Comments

0
     function a(text,function){
        return '<a href="#" onclick="myfunction();">'+text+'</a>';
     }

     function myfunction() {
        alert('test');
     }

Comments

0

I found another way using jquery

function addActionButton(caption, tooltip, callback) {
  el = jQuery('<a/>', {
    class: 'btn btn-outline-secondary',
    title: tooltip
  });
  el.click(callback);
  el.html(caption);
  el.appendTo('#buttonbar')
}

Comments

0
function foo(para1){
    console.log(para1)
}
let bar = "hello world"
someElement.onclick = function (){foo(bar)}

1 Comment

Hi there! So... it's a bad practice to "just put the code" in an answer. Could you add a little more context? Usually a small explanation of what you did would be enough. Thanks!

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.