JVE999
JVE999

Reputation: 3517

How can I write a non-clickable link that runs a javascript function upon click?

I know this question was answered before, here: javascript:void(0) or onclick="return false" for <a> - which is better?

However, the solution did not work for me.

Here's the applicable code:

HTML:

<a id="Skip">Skip</a>

Javascript:

   var Skip = document.getElementById("Skip");
   Skip.addEventListener('click', reloadPage(), true);

   function reloadPage() {
        window.location.href = "play.php";
    }

When I click on "Skip," nothing happens. I would like to keep the window.location.href method of reloading as I'd like to add $_GET variables to it.

Upvotes: 1

Views: 102

Answers (2)

Umesh Gohil
Umesh Gohil

Reputation: 46

Basically you have pass function pointer to addEventListener. So that when click happen it calls that method. You don't want to call the method coz that return nothing

For eg :

Skip. addEventListener('click', reloadPage, true);

you can also do like what you have written but only if your method return another function

for eg

Skip. addEventListener('click', reloadPage(), true);
function reloadPage() {
     return function(){
        // do something interesting.
     }
}

Upvotes: 2

gdoron
gdoron

Reputation: 150273

Skip.addEventListener('click', reloadPage(), true);
//                                       ^^-------------------

Should be:

Skip.addEventListener('click', reloadPage, true);

You want the callback to be reloadPage not what reloadPage returns.

Upvotes: 6

Related Questions