Tuesday, May 7, 2019

onclick in span not working (fixed)

Problem

I had the following HTML and JavaScript code:

<span onclick="close()">x</span>

<script>
function close() {
    doSomething();
}
</script>

My close() function was never being triggered, no matter what. It didn't even help if I made my span display: block and gave it some width and height. I clicked on my span and nothing happened.

Then, after some fiddling around, I finally figured it out. Yes, it's important to debug. I first tried alert("hi") and that worked, so I knew it had something to do with my function.

Solution

Change the function name to myClose(), then it works. This is because the close() function already exists in JavaScript and it will conflict with your close() function. I suspect this has something to do with event bubbling, but I'm not sure.

Conclusion

Don't name your function names too stock or you will risk overlapping an already existing JavaScript method. In my case, the (window).close() function already existed in JavaScript.