简体   繁体   中英

JavaScript not working when is in separate file

I have code:

$(window).scroll(function () {
    var scroll = $(window).scrollTop();
    if (scroll >= 500) {
        $(".koncecki-web-design").addClass("konecki-scroll");
        $(".top-nav").addClass("show");
        $("#work").addClass("work-margin");
    } else {
        $(".koncecki-web-design").removeClass("konecki-scroll");
        $(".top-nav").removeClass("show");
        $("#work").removeClass("work-margin");
    }
    if (scroll >= 200) {
        $(".top-text").addClass("top-text-scroll");
    } else {
        $(".top-text").removeClass("top-text-scroll");
    }
});

I have this in my index file but i want to have in control.js

<script type="text/javascript" src="js/control.js"></script> 

When i paste this code to control.js script does not work.

What could be wrong?

Thanks! Silon

Be sure to have jQuery included before control.js. So

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/control.js"></script>

instead of

<script type="text/javascript" src="js/control.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>

You need to:

  1. Check if you including control.js before jquery.js then it would not work move your jquery file to top.
  2. DOM is not ready to be worked on so move all your code to $(document).ready()
  3. Or include your control.js just before closing body tag, it will take care of above two points.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM