Amanda L Amanda L - 7 months ago 60
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?

var left = Math.floor(Math.random() * 100);
var a = document.createElement('a'); = left+'%';
a.href = '#';
a.onClick = "randomlinks()";
a.innerHTML = 'click me';

<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() {

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

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