开发者

Rails 3 and Jquery - how to use Application.js without document.ready()

I am using Rails 3 and JqueryUI-1.8.3). I have images on the page that I want the user to be able to resize.

Application.html.erb is as follows:

  <%= javascript_include_tag "application.js" %>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"></script>

When I write the code as below in my application.js, the image is resizable:

开发者_Python百科
      $(document).ready(function(){
       $("#img1").resizable({ handles:'n,e,s,w,ne,se,nw,sw' , maxHeight: 300, aspectRatio: true });

});

However, the above code has problem because the image is sometimes not loaded correctly (the page had to be refreshed to display the image). This is because though the document is ready, image has not been loaded.

So I thought of using the following in application.js to fix the need for refresh:

   $("#img1").load(function () {
  $("#img1").resizable({ handles:'n,e,s,w,ne,se,nw,sw' , maxHeight: 300, aspectRatio: true });
    });

However, this makes the image not resizable (only displays image, but no resize). The code seems to work on JSBin (http://jsbin.com/iboxoy/40/edit#source), but not in my Rails code. Anytime I do not use document.ready(), the image does not remain resizable in rails Jquery-UJS code.

  1. Does application.js file always need to have document.ready()?
  2. Why does (#img).load() not work in this case?
  3. Is there any other solution which would be more efficient.

Thanks!


Try rebinding the resizable behavior both when the document is ready, and when the image has finished loading.

$(document).ready(function(){
    $("#img1").resizable();

    $("#img1").load(function () {
        $("#img1").resizable();
    });
}


Just in case someone comes across this question in the future --

I solved it by changing

$(document).ready()

to

$(window).load()

This is because we are doing actions on the images which need to be first loaded. This resolved the issue I was seeing.

Somehow $("#img1").load() within $(document).ready() is not working. It would be great if someone could explain why this is the case. My guess is that document is ready before image gets loaded (if image is not in the cache, typical for a new user of the page and the $("#img1").load() does not get fired (Since image is not loaded when document is ready).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜