External Javascript

Hi all. I’m trying to host my random name generator on a web page. I want to hold the javascript in a separate file. The site loads, however the button does not work. I was wondering if there is something different I need to do in this case?

Here is my index.html:

<header>
 <link href="/css/css.css" type="text/css" rel="stylesheet">

 <title>Stoner Rock Band Name Generator</title>

</header>

<html>
<body>

<div class="container-fluid">
  
  <div class = "row text-center">
    <h1>Stoner Metal Band Name Generator</h1>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12 well message bigFont">
      ~
    </div>
  </div>
  <div style="text-align:center;" class = "row text-center">
    <div class = "col-xs-12">
      <button id = "getMessage" class = "btn btn-primary button buttonContainer">
        Get Inspired
      </button>

	
    </div>
  </div>
</div>

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" src="/JS/script.js"></script>
  
</body>
</html>

And here is my javascript file:

var list1 = [''blach', "blah", blah"];

var list2 = [''blach', "blah", blah"];


function showQuote(){
  var quote1 = Math.floor(Math.random() * list1.length);
  var quote2 = Math.floor(Math.random() * list2.length);
  return list1[quote1] + list2[quote2];
    }

  $(document).ready(function() {
    $("#getMessage").on("click", function(){
      $(".message").html(showQuote());
    });
  });

the JS file is at root/JS/script.js

After you load your jQuery at the bottom of the HTML file, next load your javascript file with a similar script tag.

Okay, now I have

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"</script>
 <script src="/JS/script.js"></script>

But my button still doesn’t work.

Look at your quotes here.

1 Like

sorry I just edited those out because some of the words in the arrays were NSFW. I checked the syntax in codepen and fixed all the errors before posting here. The code also works in codepen:

https://codepen.io/rivid/pen/QOxRxQ (NSFW)

As bodhi points out, your arrays and your mix of quotation marks is causing loads of syntax errors.

Also, you need a dot before your file path to ensure it’s treated as a relative path:

<script src="./JS/script.js"></script>

If you’ve got it working in codepen then the file probably isn’t loading. Check in the browser dev tools for any 404 error.

It was a syntax error, I was missing the > in the first script tag

1 Like