JQuery click event fires on second click but not on first

JQuery click event fires on second click but not on first

Hi my problem is as described above, I have had this happend before some time ago and it still puzzles me not sure why its happening.

We’re definitely going to need code samples, a live example, or something.

Ok heres the basics of it:

When I do this:

	      $("#flowplayer_play").live('click', function() {
			 $(this).click(flowplayer_play);
			});

and call this function in an external script( which is why I did it for tidyness sake)


function flowplayer_play()
{ 
var src="Images/pause.png"
  	 $("#flowplayer_play").attr("src", src).removeAttr( "id" ).attr("id", "flowplayer_pause"); 
	      $f("splash").play();
   
}

The weird click thing happens.

But when I just do plain old:


    $("#flowplayer_play").live('click', function() {
			 $f("splash").play();
   });

It works fine. But I don’t want all of my handlers and functions in the same script, I woudl like to put the handlers in the external script too but they only seem to work on the html page and cease to work when put in the script with the functions.

BTW the live() is only being used because I am adding these buttons dynamially, they aren’t always visible

The problem is with this code here (I think):


$("#flowplayer_play").live('click', function() {
    $(this).click(flowplayer_play);
});

That doesn’t execute your “flowplayer_play” method – it assigns a new “click” event listener to the element. So if you just change it to this…


$("#flowplayer_play").live('click', flowplayer_play);

…then it should work.

Thanks so much sdleihssirhc, we live and learn eh ! :slight_smile:
This happened to me ages ago and I never figured it out, always bugged me. Do you have any idea why the event handlers only work in the main html/php script and not in an external file?

Let’s look at the two scripts again:


// your first attempt
$("#flowplayer_play").live('click', function() {
    $(this).click(flowplayer_play);
});

// doing it without any external files
$("#flowplayer_play").live('click', function() {
    $f("splash").play();
});

The problem wasn’t that your code was in a different file. It’s that, in your first script, you were assigning a “click” event listener instead of firing the function.

When you just stuck $f(“splash”).play() in the code, you also got rid of that event listener assigning stuff. To make your first function work, you’d have to…


// change this line:
$(this).click(flowplayer_play);

// into this:
flowplayer_play();

Hey there thanks so much for your input on this, its really got me thinking,such an obvious error but never noticed it, all the best to you :wink:

            $(function(){
	$(document).on('click',"a[rel='external']",function(){
	window.location.href=this.href;
	});
	});