somesh
somesh

Reputation: 2579

Unable to define a click event on a href tag

I am trying to write a click event for an anchor tag in my tampermonkey script.

var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;

contentTag.innerHTML = "";

var lines = fileContents.split("\n");
window.alert("Number of lines:"+lines.length);


for(var i=0; i<20; i++) {
if(i!==15)
 contentTag.innerHTML+=(lines[i]+"<br>");
else {
    contentTag.innerHTML+=("<a id=link1>Click me</a>");
    var link = document.getElementById('link1');
    link.addEventListener("click", function() {
        window.alert('I am clicked');
    }, false);
}
}

The alert message never gets triggered when I click on the link in the page dispalyed, even though I have a a click event listener defined. What am I doing wrong here?

Upvotes: 0

Views: 386

Answers (3)

adeneo
adeneo

Reputation: 318182

It's the way you're adding HTML, you're reappending the link when you do this in the next iteration.

link.innerHTML += something

So the event handler is lost, and you can actually prove that by adding the event handler to the last element instead.
If you do it the proper way, creating elements and appending them, it works fine

var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;

contentTag.innerHTML = "";
var lines = fileContents.split("\n");

for (var i = 0; i < 20; i++) {
    if (i !== 15) {
        var txt = document.createTextNode(lines[i] || ''),
            br  = document.createElement('br');
        contentTag.appendChild(txt);
        contentTag.appendChild(br);
    } else {
        var link = document.createElement('a');
        link.id = 'link1';
        link.innerHTML = 'Click me';
        link.addEventListener("click", function () {
            alert('clicked')
        }, false);

        contentTag.appendChild(link)

    }
}

FIDDLE

Upvotes: 3

Newbie
Newbie

Reputation: 287

Try this:

<script>
var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;

contentTag.innerHTML = "";

var lines = fileContents.split("\n");
window.alert("Number of lines:"+lines.length);

for(var i=0; i<20; i++) {
if(i!==15)
 contentTag.innerHTML+=(lines[i]+"<br>");
else {
    contentTag.innerHTML+=("<a id=link"+i+">Click me</a>");
    var link = document.getElementById('link'+i);
    var att=document.createAttribute('onclick');
    att.value="alert('Clicked !')";
    link.setAttributeNode(att);
}
}
</script>

Demo: http://jsfiddle.net/TmJ38/

Upvotes: 0

AlieN
AlieN

Reputation: 543

Shoud be contentTag.innerHTML+=("<a id='link1'>Click me</a>");

Upvotes: 0

Related Questions