user7186746 user7186746 - 17 days ago 8
HTML Question

My jquery code will not work if included as a .js file?

I have written html/css code and then added another file to include the jquery library and my own js code (in the file

scripts.js
).

My code does not work if I keep it in the separate scripts.js file, but it does work if I apply it in the
<scripts></script>
element within
index.html
.

Why is this and how can I solve the problem?

My HTML code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Hartmeting</title>
<link rel="stylesheet" href="css/stylesheet.css" type="text/css">
<script src="js/jquery-3.1.1.js" type='text/javascript'></script>
<script src="js/scripts.js" type='text/javascript'></script>
</head>
<body>
<div id="wrapper">
<header id="titel">
<h1>Welcome</h1>
</header>
<!-- Menu -->
<nav id="menu">
<ul>
<li><a href="#intro"> Introductie </a></li>
</ul>
</nav>
<!-- Manual -->
<div id="content">
<!-- Intro Slide -->
<article id="intro">
<h2>Introductie</h2>
<figure>
<img src="http://placehold.it/150x150" , alt="Intro Afbeelding"/>
</figure>
<p>Zonder moeite je hart meten? Dat kan...</p>
</article>

<!-- Slide 1 -->
<article id="probleem">
<h2>Het Probleem</h2>
<figure>
<img src="http://placehold.it/150x150" , alt="Eerste Afbeelding"/>
</figure>
<p>Het probleem uitleggen</p>
</article>
</div>
<footer>
<a href="#wrapper"> To the top! </a>
</footer>
</div>
</body>
</html>



Browser Console Log:

SyntaxError: Unexpected token ')'. Expected an opening '(' before a
function's parameter list.


But it does work, if I do it like this:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Hartmeting</title>
<link rel="stylesheet" href="css/stylesheet.css" type="text/css">
<script src="js/jquery-3.1.1.js" type='text/javascript'></script>
<script type='text/javascript'>
$( document ).ready(function() {
$('content').hide();
});
</script>
</head>
<body>
<div id="wrapper">
<header id="titel">
<h1>Welcome</h1>
</header>

<!-- Menu -->
<nav id="menu">
<ul>
<li><a href="#intro"> Introductie </a></li>
</ul>
</nav>

<!-- Manual -->
<div id="content">
<!-- Intro Slide -->
<article id="intro">
<h2>Introductie</h2>
<figure>
<img src="http://placehold.it/150x150" , alt="Intro Afbeelding"/>
</figure>
<p>Zonder moeite je hart meten? Dat kan...</p>
</article>

<!-- Slide 1 -->
<article id="probleem">
<h2>Het Probleem</h2>
<figure>
<img src="http://placehold.it/150x150" , alt="Eerste Afbeelding"/>
</figure>
<p>Het probleem uitleggen</p>
</article>
</div>
<footer>
<a href="#wrapper"> To the top! </a>
</footer>
</div>
</body>
</html>

Answer

Your syntax seems to be right (well, yes, you already fixed that though). Yet your jQuery selector is wrong. In order to hide an html element through it's id you need the #prefix. That being said, your .hide() should look like this:

  $('#content').hide();

And also, here's the whole snippet:

$(document).ready(function() {
  $('#content').hide();
});

Demo