Reputation: 15
So, I have written this code in HTML and I am trying to use basic JQuery function like hide(). While the inline JQuery is working properly , the external JQuery code for the same does not work at all. Here's the code for the HTML file-
<html>
<head>
<script src="jq.js"></script>
<script src="JS.js"></script>
</head>
<body>
<p id='paragraph'>This is a paragraph</p>
<p onclick="$(this).hide()">This is second</p>
</body>
</html>
code for the jq.JS fiel which where external JQuery code is -
$('#paragraph').click(function(){
$('#paragraph').hide();
});
Upvotes: 1
Views: 515
Reputation: 260
@Cerlin Boss is indeed correct:
$(document).ready(function(){
$('#paragraph').click(function(){
$('#paragraph').hide();
});
});
will work - see fiddle
Upvotes: 0
Reputation: 619
Please check that js file is attached or not and in your code of JQUERY add this
$(document).ready(function()
{
$('#paragraph').click(function(){
$('#paragraph').hide();
});
});
In this way it will run when DOM is ready
Upvotes: 1
Reputation: 565
You can attach it right before the so that it is ran after all the elements have been rendered.
If you structure your code correctly however the position on the page doesn't matter.
$(document).ready(function(){
$('#paragraph').click(function(){
$('#paragraph').hide();
});
});
If you use the code above you can keep the reference to the js file before the head!
Upvotes: 1
Reputation: 15501
Enclose your code in $(document).ready()
$(document).ready(function(){
$('#paragraph').click(function(){
$('#paragraph').hide();
});
});
This way, the jQuery code inside will run only when the DOM is ready.
Readup: $(document).ready()
| jQuery Learning Center
Upvotes: 2
Reputation: 944451
Your JavaScript (because of where the <script>
tags are) runs before you've added the paragraph to the DOM.
It doesn't find the paragraph (since it doesn't exist yet) so it binds your click handler to nothing.
Move the script to after the paragraph (or wrap it in a function and run that function when you get a DOMReady or load event).
Upvotes: 2