Skip to content
Advertisement

JavaScript: onclick and return false

I’m using this in my HTML:

 <a href="#" onclick="preload('12345');return false;">Click</a>

It calls the function preload() on an external js-file and works fine so far.

But i have dozens of those links and would like to remove alle those “return false” and put only one directly inside the preload()-function in the js-file.

But it will always be ignored?! Does the “return false” really only work inside the onclick=”…”?

Advertisement

Answer

function preload () {
    // some code
    return false;
}

<a href="#" onclick="return preload('12345');">Click</a>

or use addEventListener

For example:

<a href="#" class="link">Click</a>
<script type="text/javascript">
    document.querySelector('.link').addEventListener('click', function (e) {
        // some code;

       e.preventDefault();
    }, false);
</script>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement