Amanda L Amanda L - 9 months ago 75
HTML Question

Why is this onclick event not working in my script?

I've got a script that makes it so a link will appear in a random position on each page visit. I have another script with a function for a list of random links so that once the link is clicked, you will be led to a random page.

However something is wrong because when clicking on this link, it does not lead you anywhere (the onClick doesn't seem to work). What can I do to fix it?

<script>
var left = Math.floor(Math.random() * 100);
var a = document.createElement('a');
a.style.left = left+'%';
a.href = '#';
a.onClick = "randomlinks()";
a.innerHTML = 'click me';
document.body.appendChild(a)
</script>

<script src="randomlinks.js"></script>


The function works fine if I'm putting it as:

<a href='#' onclick='randomlinks();'>click me</a>

Answer Source

Change a.onClick = "randomlinks()";to a.onclick = randomlinks;

There is typo in your onclick. Also, you have to provide function reference to onclick event handler instead of string.

var left = Math.floor(Math.random() * 100);

function randomlinks() {
  console.log('clicked');
}

var a = document.createElement('a');
    a.href = '#';
    a.style.right = left+'%';
    a.onclick = randomlinks;
    a.innerHTML = 'click me';
document.body.appendChild(a);
a {
  position: absolute;
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download