Web Analytics Made Easy -
StatCounter jQuery.animate() for dummies - CodingForum

Announcement

Collapse
No announcement yet.

jQuery.animate() for dummies

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • jQuery.animate() for dummies

    With me as the dummy.
    I'm a total jQuery newb, and this is my first attempt to use it.
    I'm trying to create a fallback for my css3 transitions by using jQuery.animate() inside a vanilla js function. I want to move a series of divs from point A (their current location) to point B (a new location defined inside of an array) like this:

    Code:
    function shuffle(){
    	i = 0;
    	while(i<=9){
    		$(document).ready(function(){
                               $('#div'+i).animate({
                                       top: topArray[i]+'px', 
                                       marginLeft: leftArray[i]+'px'},
                                       1500);});
                     i++;
    	}
    }
    Nothing happens when I click the link that triggers shuffle();. It doesn't even work if I change all the variables to something definite like

    Code:
    function shuffle(){
    	i = 0;
    	while(i<=9){
    		$(document).ready(function(){
                          $('#div0').animate({
                               top:'10px', 
                               marginLeft:'100px'},
                               1500);});
                    i++;
    	}
    }
    I'm pretty sure I've loaded the jQuery library correctly, with:
    Code:
    <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script>
    in the head of my page.

    Everything works when I replace the jQuery with my css transitions, so what's going on? The function is in an external js file and I'm testing locally - would those matter?

    Much thanks,
    ~gyz

  • #2
    1) Open up the error/JavaScript console of your browser and look if any errors come up.

    2) The rough equivalent to a while loop in jQuery is the each() function. And you can probably make things much easier by writing:
    Code:
    $(function(){
      $('.example').each(function(i) { // a selector that all elements that are supposed to be animated have in common; the “i” is the index of the current element in the loop
        $(this).animate({
          top: topArray[i]+'px', 
          marginLeft: leftArray[i]+'px'
        }, 1500);
      });
    });
    Note: This is written from mind right now and not tested.
    Stop solving problems you don’t yet have!

    Comment


    • #3
      ... and additionally you should learn about $(document).ready() before you continue using jQuery

      $(document).ready() defines an event handler that will (mostly) deal with the event DOMContentLoaded being fired by the browser. This will only(!) happen during the initial page load. So there is no point in putting this into a function or into a loop after the page has already finished loading.

      Comment


      • #4
        VIPStephan, I don't think the loop is necessarily the issue (well, not *the* issue), but it's good to know about the each() function for when I finally pin down the issue.

        devnull69, good to know, thanks. Yeah, like I said, I kinda jumped in head first without looking on this one. Normally, I'd have been able to find a tutorial online to point me the right direction, but that's what lead me to using ready() to begin with.

        So right now, I'm just trying to get it to animate at all, loop or no loop, variables or no variables.
        After getting rid of document.ready(), per devnull69's suggestion, I get the following, which still doesn't work.

        Code:
        function shuffle(){
             $('#div0').animate({top:'100px', left:'100px'},1500);
        }
        Nothing. Does the above look anything close to correct? Because if not, there's got to be something wrong elsewhere in my project. But again, this works when it's rewritten to only affect css transitions like this:

        Code:
        function shuffle(){
        	i = 0;
          	while(i<=10){
        		document.getElementById("div"+i).style.marginLeft = leftArray[i]+"px";
        		document.getElementById("div"+i).style.top = topArray[i]+"px";
        		i++
                 }
        }

        Comment


        • #5
          It would be nice of you if you posted all of your code because this little snippet doesn’t tell us anything.
          Stop solving problems you don’t yet have!

          Comment


          • #6
            The full code is actually several thousand lines long, a couple hundred kilobytes and a dozen or so external scripts, so I wouldn't want to post a giant wall of code and make you wade through it.

            Fortunately, after breaking my code and reverting to an earlier version I think I've narrowed the issue down, not to the jquery, but to the way I'm loading the external scripts into the page. Originally I was only linking a single script on the index, then using document.write() inside that script to get all the others included. This seemed sloppy and unstable, so I tried to change it to contain all the needed linkage in a document.body.innerHTML.

            Even sloppier, evidently, since it wouldn't do anything after that. It looks like this (all but one of the external texts removed):

            Code:
            function writeDivs(){
            	var newBody = "<script type='text/javascript' src='js/main.js'></script><div class='dynamicDiv' id='textDiv'><table id='innerTable'>&nbsp</table></div>"
            	var i = 0;
            	while (i<=447){
            		newBody = newBody+"<div class='posDiv' id='div"+i+"' onclick='checkClick(this.id)' onmouseover='checkOver(this.id);' onmouseout='checkOut(this.id)'>"+textArray[i]+"</div>"
            	i++;
            	}
            	document.body.innerHTML = newBody;
            }
            Reverting to the old write() method doesn't improve anything, though (exept that css transitions still work). But I've heard that jQuery doesn't jibe well with write() anyways.

            Still experimenting. I'll post more tomorrow.

            Comment


            • #7
              Okay, after additional testing, prodding and re-scripting this weekend, I've figured out that nothing was wrong with the jQuery as I last posted it. What was wrong had something to do with how I was loading my external js causing certain scripts from executing, and therefore stopping the rest the script.

              I still don't get it, but I'll post the cliff notes version of what was happening here in case anyone has an idea of what I was doing wrong.

              Like I've mentioned, I had almost a dozen external js files. I linked the first one to my index page, and that script loaded the rest of them - originally using document.write(). This worked perfectly for my css transitions, but when the jQuery failed to trigger, I thought it was write()'s fault and changed it to this:

              Code:
              function writeDivs(){
              	var i = 0;
              	var js = 0;
              	var jsArray = ["main","script1","script2","script3","script4","script5","script6"];
              	while (js<=6){
              		var scrpt = document.createElement("script");
                		scrpt.setAttribute("type", "text/javascript");
                		scrpt.setAttribute("language", "JavaScript");
                		scrpt.setAttribute("src", "js/"+jsArray[js]+".js");
                		document.getElementsByTagName("head")[0].appendChild(scrpt);
              		js++;
              	}
              	while (i<=500){
              		var _body = document.getElementsByTagName('body')[0];
              		var _div = document.createElement('div');
              		_div.setAttribute('class', 'posDiv');
              		_div.setAttribute('id', 'div'+i);
              		_div.setAttribute('onclick', 'checkClick(this.id);');
              		_div.setAttribute('onmouseover', 'checkOver(this.id);');
              		_div.setAttribute('onmouseout', 'checkOut(this.id)');
              		var _text = document.createTextNode(textArray[i])
              		_div.appendChild(_text);
              		_body.appendChild(_div);
              		i++;
              	}
              }
              I thought this would be a more stable way to load my js files and insert my dynamically-created divs, but it caused my css transitions AND jQuery animation to not execute when the first "transition" link was clicked.

              After a bunch of experimenting, I found that it was actually the following lines which were keeping the function associated with the first link from executing:

              Code:
              	div447.style.width = "150px";
              	div446.style.width = "150px";
              	div445.style.width = "150px";
              	div444.style.width = "150px";
              	div443.style.width = "150px";
              	div442.style.width = "150px";
              I removed the lines (setting those divs' default widths to "auto" in the css) and now everything hunky-dory. I just don't see a reason for this to break. Even changing them to document.getElementById('div447').style.width = "150px" didn't help.

              But whatever. The script works now. I just wish I understood my mistake.

              ~gyz.

              Comment


              • #8
                Of course, since I'm generating, then animated several hundred divs with this code, the jQuery takes several seconds after being clicked to animate at all. And even then its so laggy/choppy as to barely look animated at all.

                Hardly seems worth it, actually.

                I almost feel like skipping using a jQuery fallback altogether, instead having the divs change positions without animating and just including a tacky "Your browser doesn't support the html 5 features used by this site. Please use FF4+, Chrome or Opera, or continue here with a reduced user experience" warning on my index page until someone somewhere comes up with a good csstransitions polyfill.

                Comment

                Working...
                X
                😀
                🥰
                🤢
                😎
                😡
                👍
                👎