John
John

Reputation: 13

Javascript onClick not working as expected

I have one (for me) strange problem. I have pop under that open one url. i need to make when user click on some flashplayer (who is in div) I put javascript code

<script type="text/javascript">
    $("player").click(myfunc());
</script>


<script type="text/javascript">
    document.getElementById('player').addEventListener('click', myfunc(), false);
</script>

But there is problem.. this not work on click (when user click on #player), this work when user load page ( onload ) and i dont need that, i need on click to start function... Where is the problem?

Upvotes: 1

Views: 282

Answers (3)

James Allardice
James Allardice

Reputation: 166041

Firstly, you appear to be missing the # character in your jQuery selector (I'm assuming it's meant to be an ID selector because you also gave an example using getElementById), so it's currently looking an element called player, rather than an element with ID "player".

Secondly, you don't want to execute the myfunc function when you pass it to the click function. Instead, you want to pass a reference to the function (note the lack of parentheses):

$("#player").click(myfunc);

The same is true for your second example, but you are right in that when using getElementById you pass in the string without the # character:

document.getElementById('player').addEventListener('click', myfunc, false);

Upvotes: 2

nre
nre

Reputation: 1299

The thing you are doing wrong is that you do not pass the function as a reference to the jQuery click method but execute it.

Replace $("player").click(myfunc()); with $("player").click(myfunc); and everything should work as expected. The same applies to your second example.

Upvotes: 0

Joe
Joe

Reputation: 82654

You need to send function references:

<script type="text/javascript">
    $("#player").click(myfunc);
</script>


<script type="text/javascript">
    document.getElementById('player').addEventListener('click', myfunc, false);
</script>

When you $("#player").click(myfunc());, you are actually executing myfunc. @Paul pointed out that you were also missing the jQuery id identifier for you selector.

Upvotes: 0

Related Questions