jQuery - Running slow?

Hi all

I have adapted this code to get the effect I’m after here

http://www.ttmt.org.uk/forum/1_scrollFade/

I have div’s stacked on top of each other, the opacity of them has been dropped.

As you scroll the div most centeral will increase it’s opacity while the other will still be dropped.

The code works fine but it can be really slow and there is a delay before the div’s fade in and out.

Can anyone explain why it slow and is there a quicker way of doing this.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

	<title>untitled</title>
	<style type="text/css" media="screen">
	 *{
	   margin:0;
	   padding:0;
	 }
	 #one,#two,#three{
	   width:600px;
	   margin:20px auto;
	   height:700px;
	   background:red;
	 }
	 
	</style>
</head>

<body>
  <div id="one"></div>

  <div id="two"></div>
  <div id="three"></div>
  
  
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"type="text/javascript"></script>
  <script type="text/javascript">
    
    $('div').each(function(){
      $(this).fadeTo('fast', .2);
    })
    
    $('#one').fadeTo('fast', 1);
    
    $(window).scroll(function() {
        var midDiv = null;
        var centre = window.scrollY + window.innerHeight / 2;
        $('div').each(function() {
            var div = $(this);
            if (div.offset().top <= centre && div.offset().top + div.height() >= centre) {
              div.fadeTo('fast',1);
            }else{
              div.fadeTo('fast',.2);
            }
        });
    });
    
  </script>
</body>
</html>


What does “slow” mean? As in, your pc hangs for a bit before it’s able to render the effect?
What processor do you have and which browser are you using? How much memory is your browser taking up (bring up task manager if you’re on Windows) and what’s the CPU usage?

I tried the page in Firefox 3.6 and Chrome 9.x and I haven’t noticed any significant differences in rendering speed, and I was using rather old CPU (AMD x2 4200) so there must be something like you having tons of tabs open or some other process eating up your resources.

I’ve tried it on a few different computers and it seems slow on them all.

I would like the effect to take between 1-3 secs.

At the moment it can be anything from 3 - 8 secs, I would wait for 8 secs for a simple fade

I’d recommend you read this article:
http://dev.opera.com/articles/view/efficient-javascript/?page=3

Aside:
The URI you provided renders fine (FF 3.6)

This is the sort of speed I would like

http://www.ttmt.org.uk/forum/1_scrollFade/div_Scroll_fast.html

The problem here is I can’t now fade the divs out

This is a lot slower but the div’s fade in and out

http://www.ttmt.org.uk/forum/1_scrollFade/