/    Sign up×
Community /Pin to ProfileBookmark

Please help me understand this code

Hi

I’ve found a script that makes a div scroll across and down the page as the page is scrolled. I’ve got it to work but I do not fully understand how it works which will not help me in future so could some one help please!?

For the most part I do understand what it does but there are a few lines of code I’m not sure of.

  • 1. var yPos = (document.all ) ? document.body.scrollTop : window.pageYOffset;
  • I understand this initialises a variable but what I don’t understand is what the document.all does (something to do with IE4 but other than that I’m baffled) and basically I don’t see what any of the rest of the line does/means.

  • 2. var divStyle = (document.getElementById) ? document.getElementById(divID).style : ( (document.all) ? document.all[divID].style : document.layers[divID] );
  • Again is a variable and divID is the name of the element on the page that is to scroll, but I’m not sure of the rest of the line?

    If someone could explain this to me I’d be grateful as I hate not understanding how stuff works, specifically what the question marks and colons are used for in these lines?!

    Many thanks for any help you can give me

    to post a comment
    JavaScript

    1 Comments(s)

    Copy linkTweet thisAlerts:
    @Orc_ScorcherApr 20.2006 — ?: is the so-called 'conditional operator'. To put it simple it's a shortcut to for if-else statements. For example,variable = a ? b : c does the same as if (a)
    variable = b
    else
    variable = c
    Your first example tries to find how far the page is currently scrolled down. This is done by checking whether the browser supports document.all and assuming that the browser must be IE if it does.

    The second line finds an element's style object, based on its id. It tries getElementById first, then the old methods from the v4 browser days. Because IE4 and Netscape 4 are pretty much dead it's a bit of a waste but it doesn't hurt either.
    ×

    Success!

    Help @mcleod spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 6.17,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @nearjob,
    tipped: article
    amount: 1000 SATS,

    tipper: @meenaratha,
    tipped: article
    amount: 1000 SATS,

    tipper: @meenaratha,
    tipped: article
    amount: 1000 SATS,
    )...