Johnson
Johnson

Reputation: 818

jQuery: run only once

Yes i have an fancybox. It auto opens if ?mode=new

What happens on ?mode=new is:

<script>
$(document).ready(function(){
$('#newPM').click();
});
</script> 

It opens fine. But when you then click on the element, it keeps closing/open, because this is activated. So how can i only run this once?

Upvotes: 1

Views: 2825

Answers (2)

brian brinley
brian brinley

Reputation: 2364

A better solution is to refactor your code to not emulate the click event of another element.

Emulating human interaction to shorthand your code sounds like a great idea, until you forget that something is dependent on that "click" handler.

what you really shoudl to is have something like

<script>
$(document).ready(function(){
   'check for url variable: 
   if (urlVar(something)) {
       doSomething();
    }
   $('#newPM').click(doSomething);
});
function doSomething(e) {
 'actionable code here
}
</script> 

This way your actions and your event handlers are independent from each other.

Upvotes: 1

Amir Raminfar
Amir Raminfar

Reputation: 34149

Do you mean it keeps opening and closing the fancybox? You can do

$("#newPM").unbind("click"); 

This will remove the onclick event so it doesn't get triggered anymore.

Upvotes: 3

Related Questions