James Mallon
James Mallon

Reputation: 1127

Javascript onClick() event not working when used dynamically

I'm struggling to make the onclick event listener work in my results. here is my code:

function createLink(text, parentElement) {
        var a = document.createElement('p');
        var linkText = document.createTextNode(text);
        a.appendChild(linkText);
        temp1 = text.replace("/","-");
        temp2 = res1.replace("/","-");
        a.onclick=function(){goMainMenuFromResults();};
        parentElement.appendChild(a);
        var br = document.createElement('br');
        parentElement.appendChild(br);
}

The line in question is:

a.onclick=function(){goMainMenuFromResults();};

The function is present in another section but works in the hardcoded html events. I just can't make it work when its imported into the element in javascript. Any help will be greatly appreciated!

Upvotes: 0

Views: 60

Answers (2)

ManoDestra
ManoDestra

Reputation: 6473

I removed the lines containing variables that were not defined. I then added a call to preventDefault() on the event raised inside the event handler. And it now works fine. New elements are created and the click handler works on the new elements.

function createLink(text, parentElement) {
    var a = document.createElement('p');
    var linkText = document.createTextNode(text);
    a.appendChild(linkText);
    //temp1 = text.replace("/","-");
    //temp2 = res1.replace("/","-");
    a.onclick = function(e) {
        e.preventDefault();
        goMainMenuFromResults();
    };
    parentElement.appendChild(a);
    var br = document.createElement('br');
    parentElement.appendChild(br);
}

Upvotes: 0

Marcel Kohls
Marcel Kohls

Reputation: 1865

James, it seems to work fine, just a var called res1 was getting error here. Take a look:

temp2 = res1.replace("/","-");

http://jsfiddle.net/MarcelKohls/23tBM/291/

Upvotes: 1

Related Questions