A
A
asd dsa2018-12-30 20:17:30
JavaScript
asd dsa, 2018-12-30 20:17:30

How to fix error when switching to another html page?

I do the layout using gulp, from the src / js folder I collect all the scripts into one minified one, which I connect to the html files. So, on the index.html page, my build/all.js is connected on this page, the scroll code is used, but when I switch from the index.html page to view.html where build/all.js is also connected, I get an error: Uncaught TypeError: Cannot read property 'style' of undefined. Because there are no those elements, c index.html on which the code was written. So, how to properly organize the js connection, or organize the code so that it works only on those pages where it is used?

index.js:

const opacity = document.getElementsByClassName('move-img');

function showDivs() {
    var top = $(document).scrollTop();
    if ( top >= 100 && top < 400) {
        $('.servicies-right').stop().animate({
            'margin-right': '100px',
            'opacity': '1'
        }, 1000);
        opacity[0].style.opacity = '1';
        }
        else if (top >= 400 && top < 600) {
            $('.servicies-left').stop().animate({
                'margin-left': '100px',
                'opacity': '1'
            }, 1000);
        $('.servicies-right').stop().animate({
            'margin-right': '100px',
            'opacity': '1'
        }, 1000);
        opacity[0].style.opacity = '1';
        opacity[1].style.opacity = '1';
        }
        else if (top >= 600) {
            $('.right2').stop().animate({
                'margin-right': '100px',
                'opacity': '1'
            }, 1000);
        $('.servicies-left').stop().animate({
            'margin-left': '100px',
            'opacity': '1'
        }, 1000);
        $('.servicies-right').stop().animate({
            'margin-right': '100px',
            'opacity': '1'
        }, 1000);
        opacity[0].style.opacity = '1';
        opacity[1].style.opacity = '1';
        opacity[2].style.opacity = '1';
        }
}

var timer = null;
$(window).scroll(function () {
    clearTimeout(timer);
    timer = setTimeout(showDivs, 300);
});


index.html: view.html:

<script src="build/js/all.js"></script>



<script src="build/js/all.js"></script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alex, 2018-12-30
@yaNastia

const opacity = document.getElementsByClassName('move-img');

if (opacity.length) {
  // код
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question