Reputation: 55
So I'm a beginner in JavaScript.
I have this simple HTML file where I tried to test jQuery with $("h1").hide()
and my problem is that the jQuery code works in the HTML but when I try to put this code in an external JavaScript file testjs.js and insert it via script
tag to the head
, it doesn't works anymore. Just to be clear, the external JavaScript file is recognized, for example when I put document.write("third test")
in the external JS file it will show "third test".
Hope I've been clear
<!doctype html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8"/>
<script src="jquery-3.3.1.min.js"></script>
<script src="js/testjs.js"></script>
</head>
<body>
<h1>first test</h1>
<p>second test</p>
<!-- this works only here but not in external js file
<script>
$("h1").hide();
</script>
-->
</body>
</html>
Upvotes: 0
Views: 80
Reputation: 33736
The problem is regarding to document loading execution. The execution of $('h1').hide()
is happening just before the document is fully loaded.
<script src="js/testjs.js"></script>
</body>
DOMContentLoaded
and put the logic of hiding within it.document.addEventListener("DOMContentLoaded", function(event) {
$('h1').hide();
});
ready
from jQuery$(document).ready(function() {
$('h1').hide();
});
Upvotes: 2
Reputation: 51
It could be that the DOM has not loaded the h1 element you are trying to hide. Try using this code in testjs.js.
$(document).ready(function() {
$('h1').hide();
});
When manipulating elements you should wait for the document to fully load.
Upvotes: 4