Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adapting a coffeescript to use window.onload

Tags:

coffeescript

I have the following coffeescript, which works except for the fact that when images take a while to load it runs before the images are loaded and then doesn't have the desired effect:

ready = ->
  jQuery ->
    $('.box').find('img').each ->
      imgClass = if @width / @height > 1 then 'wide' else 'tall'
      $(this).addClass imgClass
      return
    return


$(document).ready(ready)
$(document).on('page:load', ready)

How can I run my function only after the entire window is loaded?

My best attempt so far looks like

window.onload = ->
  $('.box').find('img').each ->
    imgClass = if @width / @height > 1 then 'wide' else 'tall'
    $(this).addClass imgClass
    return
  return

but it doesn't work. I've tried several other possibilities too but I can't figure out whats wrong.

My question is different from this one since I don't want to wait until all the coffeescripts have finished loading, I want to wait until all of the images in my webpage have loaded.

like image 739
Dennis Avatar asked Sep 26 '15 17:09

Dennis


1 Answers

To execute your desired code AFTER all images are loaded, use jQuery's load() method on the window. document watches the DOM, while window watches the contents.

In coffee, it would look like this:

$(window).load ->
  alert 'All images are loaded'

The difference between this and what you had is you were using window.onload whereas I'm suggesting $(window).load().

like image 187
Wes Foster Avatar answered Oct 09 '22 22:10

Wes Foster