'When the JavaScript is within the html it works when it outside it doesn't

I use the following JavaScript .. when it is written inside the html file it works:

<script type="text/javascript">
        var d=new Date();
        var ShowenYear = d.getFullYear();
        var Month = d.getMonth();
        var NextSeason = "Unknown Season";

        if (Month == 1 || Month == 2 || Month == 3) {
            NextSeason = "Spring";
        }
        else if (Month == 4 || Month == 5 || Month == 6) {
            NextSeason = "Summer";
        }
            else if (Month == 7 || Month == 8 || Month == 9) {
                NextSeason = "Autumn";
            }
                else if (Month == 10 || Month == 11 || Month == 12) {
                    NextSeason = "Winter";
                    ShowenYear++;
                    }
        
        document.getElementById("Season").innerHTML = NextSeason + " " + ShowenYear;
    </script>

It works perfectly fine, but when I created a js file copied it all (exact same just without the script tag.

Then called the file like so:

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

it simply doesn't work.



Solution 1:[1]

<script language="Javascript" type="text/javascript" src="js/showdate.js"></script>

try to write this line of code inside the <head> tags. Then add <body onload="showdate();"> so that the function is called everytime the page loads.

    function showdate(){
    var d=new Date();
            var ShowenYear = d.getFullYear();
            var Month = d.getMonth();
            var NextSeason = "Unknown Season";

            if (Month == 1 || Month == 2 || Month == 3) {
                NextSeason = "Spring";
            }
            else if (Month == 4 || Month == 5 || Month == 6) {
                NextSeason = "Summer";
            }
                else if (Month == 7 || Month == 8 || Month == 9) {
                    NextSeason = "Autumn";
                }
                    else if (Month == 10 || Month == 11 || Month == 12) {
                        NextSeason = "Winter";
                        ShowenYear++;
                        }

            document.getElementById("Season").innerHTML = NextSeason + " " + ShowenYear;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1