change the corresponding line to:
elm.setAttribute("onclick", function() { alert("you clicked a link");});
If you pass as argument a function call (such as alert('msg')), the function is executed imediatley and the actual passed argument is the function's return value. All you have to do is wrap your eventHandler code into an anonymous function.
Also, you can declare a function that handles your event and send it's name as argument :
function handleClick() { alert("you clicked a link");}
elm.setAttribute("onclick", handleClick);
P.S. : I recommend using the addEventListener functionality instead of plain old onEvent inline attributes :
elm.addEventListener('click', function() { alert("you clicked a link");}, false);