Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ready function is called twice

Tags:

jquery

This is my html

<div id="projekt" style="position: relative; width: 90%;height:400px;"/>

 $("#projekt").ready(function() {

     .. do something with the div
 });

The problem is the ready function is called twice. What could be the reason ?

like image 585
user137348 Avatar asked Nov 05 '10 15:11

user137348


6 Answers

If you include your javascript file twice, it'll be executed twice. This doesn't show up clearly in firebug. The script panel (where I went to debug the javascript problem) will only show the file once in the dropdown. But if you look in the html or net panels you can see if there are multiples.

I had something like:

<script src="/scripts/project.js" type="text/javascript"></script>
<script src="/scripts/project.js" type="text/javascript"></script>

(This is similar to @chs answer, but not specific to rails.)

like image 109
Joe Flynn Avatar answered Nov 16 '22 04:11

Joe Flynn


There's a bug which can cause this. Try updating or binding to the document instead of the div.

like image 29
Craig Stuntz Avatar answered Nov 16 '22 03:11

Craig Stuntz


I found a solution to this problem.

You should use this code

$(document).bind("ready", MyDocumentReadyHandler)

instead of the code

$(document).ready(...);

You can read more about the "ready" function using this url.

like image 36
user1091132 Avatar answered Nov 16 '22 04:11

user1091132


I have seen this happen when I have an alert('...'); somewhere inside the .ready callback. This happens as recently as jQuery 1.5.2. Taking the alert out makes the code only run once.

like image 22
KevinM Avatar answered Nov 16 '22 02:11

KevinM


No need to add application option at the following tag in config/application.rb config.action_view.javascript_expansions[:defaults] = %w(jquery application)

It will call applcation.js twice, so the functions also runs twice in your application

like image 40
chaitanya Avatar answered Nov 16 '22 02:11

chaitanya


if you have a wrong src in iframe like <iframe src="../" ...></iframe>, the function ready() will be executed twice. Make sure you have a valid URL.

Ex.:

<iframe src="../something.html" ... ></iframe>
like image 33
Fábio Almeida Avatar answered Nov 16 '22 02:11

Fábio Almeida