JavaScript from Null: Chapter 4
basixvideos

JavaScript from Null: Chapter 4

This entry is part 4 of 7 in the series javascript-from-null

The Full Series

JavaScript University continues today as we learn about methods of the Array object, how to return values from functions, scope, and even your first animation.

Remember – though each new chapter builds upon the previous ones, you can still follow along perfectly well if you haven’t watched the other entries in the series!

In this Screencast, you’ll Learn:

  • Methods of the Array object: push, pop, unshift, shift
  • Pull values outside of functions
  • Reducing your “global footprint” by creating an object
  • SetInterval
  • Create your first animation
  • Methods of the String object.

Chapter 4: Arrays, Functions, and your First Animation

Other Viewing Options

Ready to take your skills to the next level, and start profiting from your scripts and components? Check out our sister marketplace, CodeCanyon.

CodeCanyon


Series Navigation«JavaScript from Null: Chapter 3JavaScript from Null: Chapter 5 – Events»

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.engram.nu Niklas

    Great! I have been waiting for this! This is truly a great series Jeff. Thanks a lot!

  • http://rcanblog.com Aashish

    Thanks for this series, I am waiting for advance things

  • slier

    Thx…

  • viaria

    this is really helpfull and good appetite

  • http://www.virtualerik.com Erik

    Brilliant as usual! Thank you very much for producing these series.

  • http://xsaiddx.0fees.net kosaidpo

    nice tut ilike it very interestin tnx jeff

    can u please make it more fun and teache us how we can make simple games like tetris or sumthin simple that wud be so rad and good trainin tho

    tnx again for ur time n effort

  • http://www.centrak.net/ Kyle Briody

    This series started around the time I wanted to sit down and learn raw javascript and I couldn’t be more happy. Thank you very much Jeff!

  • Ludwik

    Great one!

    But IMO You should stop this setInterval function (by clearInterval), when opacity is equal 0. There is no reason to force CPU to think 50 times per secound when there is nothing to fadeout.

    • http://net.tutsplus.com Jeffrey Way

      Ludwik – Absolutely. That will be refined in the next chapter. :)

  • Micko

    Very useful tutorial.

  • miaousse

    hi Jeff

    What happen to the function fadeOut when the opacity comes to zero. Does it loop endlessly?

    • http://net.tutsplus.com Jeffrey J Way

      No – remember how we checked to see if the current opacity is greater than zero? If it’s not, that means the opacity is in fact at zero – in which case we don’t do anything.

      We’ll refine this function much more in the next lesson.

      • Richard

        I may be wrong but it looked to me as if we were just checking to see if an opacity value existed and not whether it was greater than zero, and even then it only assigns 1 to the opacity I don’t think it stops the function. In that case it would keep looping would it not? I mean it hits zero but it still has a value so it keeps going into the negatives.

        Again I’m new at this so I may be way off, either way thanks a lot Jeff for the screencasts, I hope there are many more.

        Side note: when trying to watch this again to check if I missed something about this it started playing some web tv show instead … odd.

  • Jermaine

    Thank you for these tuts, my leacture makes this all sound so dull but you make it look much simpler. Keep up the good work

  • http://www.equali.com Stephen

    thank you for your time and effort… it is greatly appreciated.

    kudos, thanks and happy new year.

  • http://www.what-a-geek.com Adit Gupta

    Great series!! :)

  • http://smashingwebs.com/ SmashingWebs.com

    Ya.. great series.. looking forward for more :)

    http://smashingwebs.com/

  • http://manduks.wordpress.com/ manduks

    hi there only an observation on the fading function you use

    elem.style.opacity three times,

    you talk on a first best practice to put the accesing Dom variable from outside of de function another best practice will be

    to asign elem.style.opacity to a var in the function so that way it run faster

    function fadeOut(elem,speed){
    var elemOpacity = elem.style.opacity;

    //elemOpacity = elemOpacity || 1 ;

    if(!elemOpacity ){
    elemOpacity = 1;
    }
    setInterval(function(){
    elemOpacity -=.02;
    },speed/50);
    }

    and great tutos I really enjoy coming to this web every day :)

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Exactly. Great eye. In the next lesson, we’re going to greatly improve that function. :)

    • Andras

      Are you sure, this works?
      Why would these to calls

      elemOpacity = 1;
      elemOpacity -=.02;

      update the elem opacity value? It updates only the variable, but not the element itself, right?

  • Edison Leon

    can wait for the next one, thanks!

  • Edison Leon

    can’y wait for the next one, thanks!

  • Helen

    Jeff, you’re doing well and I can see it might be necessary to do some calculations with JS, but mostly a webdesigner needs things like finding elements in the DOM and doing something with it.

    I’d like to know the basic syntax of (1) getting the objects and (2) telling JS what to do with it.

  • http://www.pioneer-physicaltherapy.com/buy-generic-clomid-online.html clomid success rates

    I really like your blog and i respect your work. I’ll be a frequent visitor.

  • Ahmad Fawaz Amin

    Great tut Jeff, but one thing I was curious about.

    Wouldn’t it be better( user friendly ) if you do this.

    function fadeOut( elemId, time ){
    var elem = document.getElementById( elemId );

    setInterval( function(){
    elem.style.opacity -= .02;
    }, speed / 50 );

    }

    instead of doing getElementById every time you want to fadeOut a new element.

    • Andras

      Actually, I was wondering about the same thing, but it doesn’t work for me and I don’t know why:

      function fadeOut(elemId, speed) {
      var elem = document.getelementById(elemId);
      if ( !elem.style.opacity ) {
      elem.style.opacity = 1;
      }
      setInterval(function(){
      console.log(elem.style.opacity);
      elem.style.opacity -= .02;
      }, speed / 50);
      };
      fadeOut(‘box’, 1000);

      What’s the problem here?

      • Andras

        Never mind, I got it :)

        getElementById with capital ‘E’

  • http://emitgraphics.com Zak Groner

    Absolutely loving this! Watching these vids are the easiest way to learn any language. Jeffery Way pretty much taught me how to write CSS, and now I’m well on my way to learning Javascript.

  • Andrew

    Really loving this series, great work!

  • Jonathan Sells

    Hi Jeff,

    Thanks for this set of tutorials again…wondering if you could get to asset preloading…that is something I’d love to get your input on.

    Cheers.

  • Jonathan Sells

    Hi Jeff,

    Thank you again for this great series, really learning a lot. I was wondering if/are you going to get into asset preloading…this is something that I’d love your input on.

    Cheers.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Sure – I’ll make a note to teach how to preload images.

  • flash

    Its nice to see that your still applying emphasis on understanding old fashioned javascript.. I hope these JQuery minded youngsters benefit from this series.

    Great job!

    • http://nicolahibbert.com Nikki

      This “jQuery minded youngster” is certainly benefiting from learning how to do things from scratch :)

  • http://www.ricardofilipe.com Ricardo Magalhães

    Thank you once again Jeff, I am learning more about Javascript with your videos than with any other online tutorial, which either moves too slow or too fast at some point. I truly appreciate your efforts, and your decision to provide them free of charge. I really hope you’ll keep doing these, at your own pace of course, until we’ve all created a super framework of our own ;)

    If I ever build a js framework, I’ll call it jWay out of respect! (Hey it actually sounds quite cool, doesn’t it?)

    Keep doing them, I’ll keep wathcing them. That’s a promise.
    My regards!

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Yay!

  • http://www.TylorSkory.com Tylor Skory

    As always, great tutorial! Looking forward to the next one. I also agree that the jquery vs Javascript was helpful and would like to see more of it in future tutorials!

  • http://www.suntemtoti.ro Marius

    hello,
    Excuse my english, but i was wondering, don`t we need to stop the interval after the opacity of the box/image si === 0 ? because, it will run even if the element is gone, and it will run for no reason.

  • http://thejavascriptblog.com Merrick Christensen

    This looks great, I noticed someone already commented on the issue of never stopping the function. Maybe when you do the follow up on that… Add some call backs? :)

  • Gisele

    Didnt work on IE 8!

  • http://www.techonia.com Fuad NAHDI

    Very good and great tutorial.

  • Manny

    Desperately waiting for part five! You are my hero Jeff

    • Bryan

      I most definitely second that !

      Love these javascript series ;)

      It gets me up to speed quickly without reading another book.

  • http://bluetreemedia.ca Scott

    Great tutorials! I can’t wait for the next part!

    THanks

  • http://www.benjamin-franck.com Ben

    These were great to follow !!
    Will there be a 5th part ? ^_^

  • http://we-design.eu Dominic

    Thanks Jeff this is a great tutorial and series!!

    declaring all the vars bugged me though xD

    function fadeOut(elem){
    var elem = document.getElementById(elem);

    fadeOut(‘box’);

  • http://www.subash.net.np Adikari

    thanks for this great series.. And hope to get more such posts..

  • Wasabi

    Where are the code downloads for lessons 2 – 5?

  • Alex

    Hay Jeff awesome Tutorials I am learning a lot. I was wondering if you are going to get into JSON and AJAX in this series?

  • Deoxys

    One thing, please stop using this “show all windows” thing. It’s pretty nerv-racking. Use Command + Tab instead. THX

    Tutorial is great again :)

  • Maher Salam

    Thanx Jeff for this excellent tutorial, no one could have done it in a better way then you did!

    I have 2 things that I couldn’t figure out yet:

    1- I tried to stop the function from continuing with decreasing the value of the opacity by using :

    ################################
    while(elem.style.opacity !== 0) {
    setInterval(function() {
    elem.style.opacity -= 0.05;
    }, speed);
    }
    ################################

    But the browser keeps crashing (Chrome and FF)!

    2- I tried to do the opposite thing which is fading in an element using the same technique:

    ################################
    var box = document.getElementById(“box”);

    function fadeIn(elem, speed) {
    if( !elem.style.opacity ) {
    elem.style.opacity = 0;
    }
    setInterval(function() {
    elem.style.opacity += 0.5;
    }, speed);
    }

    fadeIn(box, 30);
    ################################

    But nothing happened! I tried the console to log what’s happening and it logged the value of the opacity… the strange thing that the value didn’t increase by “0.5″ every 30 ms, instead it was keeping the “0.5″ value without changing!

    I hope you understand the problems, I tried to explain them in the best way I can (taking that English is not my first language ^^)!

  • Hesham Rashedy

    Great work from person that deserves appreciation,

    * can you share the plan for this tuts,
    * and another request can i build another version from this tuts in Arabic language was based on your good work and published in your sites.

    thank you Jeff..

  • http://twitter.com/kaizer1v Kaizer1v

    Hey Jeff. Have a Question.

    When I write

    var myArr = ['one', 'two', 'three', 'four'];
    console.log(myArr);

    myArr.push(‘five’);
    console.log(myArr);

    Ideally I expect the output to be

    ["one", "two", "three", "four"]
    ["one", "two", "three", "four", "five"]

    But instead, it gives me

    ["one", "two", "three", "four", "five"]
    ["one", "two", "three", "four", "five"]

    How does the value of the 1st console.log(myArr) also has the element “five”?

    Looking forward to the answer. Thanks.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Are you sure? It should echo out as you expected.

  • http://twitter.com/kaizer1v Kaizer1v

    Yup I tried that once again and turns out that when I write

    myArr.push(‘five’);
    consloe.log(‘After pushing five’ + myArr);

    displays the right answer but if I don’t write the text before, it gives me the output that I previously wrote (the comment above yours). Also, I believe the parser when it reads the code is not in a linear fashion for all variables and funcitons. For example, if I split my code in two separate tags it is unable to identify and call the functions which are mentioned in the 1st script tag.
    Neverthless, I shall find out a solution. Thanks for the help.

  • chichibek

    aja jeffry te salio un bucle infinito

  • Dougieladd

    Hi Jeffrey,

    You know the Function “fadeOut” at the end of this tut?… Is this a reserved javascript function name?, and the things in parenthesis are it’s parameters? So… “elem” and “speed” are also reserved javascript parameters too? So when you call fadeOut (myImg, 2500)… “myImg” is actually the “elem” param and the “2500″ is the speed?

    Hope you understand my question… I’m not that great with this kind of coding (presentational markup is more me, but I want to learn to use this stuff (instead of just using the jquery library) so I’m making it as completely simple as possible for myself (i.e. imagine you’re explaining the answer to a monkey with attention deficit disorder (thats me :)

    Many thanks

    • http://www.frendz4ever.in Fahad

      Hi there,
      elem,speed and fadeOut are not reserved parameters and you can give them any name you want.Hope this helps you and i hope its not a late reply from me lol as i have just started.

  • Chintan

    Hey Jeff, great tutorial, helped me learn a lot.

    Why not put the getElementById bit in the function itself? Saved me time.

  • R. Thor

    I redefined mine to look like this….

    function fadeOut(elem, sec) {
    var element = document.getElementById(elem);
    var speed = sec * 1000;

    if(!element.style.opacity) {
    element.style.opacity = 1;
    }

    setInterval(function() {
    element.style.opacity -= .02;
    }, speed / 50);
    }

    fadeOut(‘o’, 2);

  • Fahad

    Hi,
    Thank you for this great tutorial jeffrey its easy to learn from your tutorials.
    I have completed chapter 3 and now i am working on chapter 4 but i am a bit confused on the Reducing your “global footprint” by creating an object part.

    This is what you have shown in screen cast

    var myObj = {
    var1 : ‘something’,
    var2 : ‘somethingelse’,
    another : function(){
    alert(‘Hello! world’);
    }
    };
    alert(myObj.another());

    But when i save it open it in firefox it shows me 2 alert box first is Hello! world an second is undefined.I made a change to this code

    var myObj = {
    var1 : ‘something’,
    var2 : ‘somethingelse’,
    another : function(){
    alert(‘Hello! world’);
    }
    };
    myObj.another();

    This shows only one alert box but how is this possible? Your screen cast video shows only one alert box for the first code.
    Awaiting for your reply

    Thank You.

  • Paul

    you rock dude …. thank you sooo much
    you got me hooked , got me reading the Javascript “the definitve guide”
    Learning at the same time form multiple sources but yours rocks the most ….

    keep it up ….

  • Oscar

    Great tutorial!

    I have some problem when im trying to implement this into a eventListener. Im already spawning the element on a eventListener. But I wanna add another function where I can fade the element in.

    var hiddenElement = document.getElementById(‘hiddenElement’);

    hiddenElement.addEventListener(‘click’, fadeIn, false);

    function fadeIn() {
    setInterval(function() {
    hiddenElement.style.opacity += .08;
    }, 1000 );
    }

    Any help would be appreciated :)