Search code examples
javascriptcssselectors-api

Javascript queryselector.style.modify "uncaught TypeError"


    <script type="text/javascript">
    var ypos,sH,sH6,sIMG,sH4,sP;
        function trigger(){
        ypos=window.pageYOffset;
        /*..............................................Second page...*/
        sH=document.querySelector("#second h2");
        sH6=document.querySelector("#second h6");
        sIMG=document.querySelectorAll("#second img");
        sH4=document.querySelectorAll("#second h4");
        sP=document.querySelectorAll("#second p");
        /*.....................................Second page trigger...*/

        console.log(ypos);
            sH.style.opacity=0;
            if(ypos>120){ 
            sH.style.opacity=1;
            sH.style.transition="3s";
        };
            sH6.style.opacity=0;
            if(ypos>200){ 
            sH6.style.opacity=1;
            sH6.style.transition="3s";
        };
            sIMG.style.opacity=0;
            if(ypos>320){ 
            sIMG.style.opacity=1;
            sIMG.style.transition="3s";
        };
            sH4.style.opacity=0;
            if(ypos>400){ 
            sH4.style.opacity=1;
            sH4.style.transition="3s";
        };
            sP.style.opacity=0;
            if(ypos>480){ 
            sP.style.opacity=1;
            sP.style.transition="3s";
        };

        };

     window.addEventListener("scroll",trigger);
    </script>

When I try to modify "style" I get error

Uncaught TypeError: Cannot set property 'opacity' of undefined

I find out that is node list, I was trying to add[0] because its a first element, but with no luck. How to define a object?

I usually use ID's but now I have lot of elements to animate.

I am new to javascript and I don't know how to use jQuery


Solution

  • document.querySelectorAll returns NodeList, you need iterate over it

    So for getting first element you can via [0]

    sIMG[0].style
    

    But document.querySelector doesn't return NodeList, it returns the first matching element. Here you don't need get first element via [0]

    sH[0].style.opacity=0;  
    // ^-- error here
    

    It should be:

    sH.style.opacity=0;