Search code examples
javascriptjqueryhtmlcssgsap

Using CSS classes as jQuery variables


To my understanding, in jQuery you can set a variable then use it later down the line.

var x = 2;
function add() {
    x = x + 2;
}

In my code, I have a CSS class as a variable.

var scroll = $('.verticalScrollBar');
function changeScrollBar() {
    ...
    TweenMax.set(scroll, {css:{height:scrollBarHeight+'%'}});
    ...
}

However, this does not seem to work. Initially, I thought it might have been a problem with GSAP TweenMax so I tried the following code.

function changeScrollBar() {
    ...
    TweenMax.set($('.verticalScrollBar'), {css:{height:scrollBarHeight+'%'}});
    ...
}

To my surprise this did work. So my question is why does the line of code TweenMax.set($('.verticalScrollBar'), {css:{height:scrollBarHeight+'%'}}); work but this line of code TweenMax.set(scroll, {css:{height:scrollBarHeight+'%'}}); does not?

Working example JSFiddle

Broken example JSFiddle


Solution

  • Changing:

    var scroll = $('.verticalScrollBar');

    To:

    var scroll = '.verticalScrollBar';

    Results in your broken example operating as expected.

    .....

    Edited (twice now) for an explanation as to why this is happening.

    As @Katana314 pointed out, the var scroll bit is defining a jQuery object that doesn't exist at this point. $(".verticalScrollBar"); doesn't exist until after changeScrollBar() is executed.

    Using var scroll = '.verticalScrollBar' works because you're not declaring a nonexistent jQuery object. You're simply providing a bit of text, which CAN be matched to the object once it has been created.