Siva Natalie Siva Natalie - 2 months ago 9
Javascript Question

inline javascript trigger doesn't work

html = '<a href="#" onclick="alert("This link is clickable only in the mobile!")">text</a>'


I append my html but when I click it says Unexpected token }, is it impossible to do the inline trigger like that?

Answer

You need to escape the " characters in property values... Use the &quot; special entity:

html = '<a href="#" onclick="alert(&quot;This link is clickable only in the mobile!&quot;)">text</a>'

There are better options to achieve this instead of writing raw HTML in JavaScript.

jQuery:

var aElement = jQuery("<a>").attr("href", "#").click(function() {
    alert("This link is clickable only in the mobile!");
});
// You can append it like:
aElement.appendTo(document.body);

Pure Javascript:

var aElement = document.createElement("a");
aElement.setAttribute("href", "#");
// If you want the onclick attribute to show up in HTML source:
aElement.setAttribute("onclick", "alert(\"This link is clickable only in the mobile!\")");
// This way is easier:
aElement.onclick = function() {
    alert("This link is clickable only in the mobile!");
}
// Append like:
document.body.appendChild(aElement);