Rhythm garg
Rhythm garg

Reputation: 15

External JQuery not working

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

Answers (5)

mcabe
mcabe

Reputation: 260

@Cerlin Boss is indeed correct:

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

will work - see fiddle

Upvotes: 0

varad mayee
varad mayee

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

greatTeacherOnizuka
greatTeacherOnizuka

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

Rahul Desai
Rahul Desai

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

Quentin
Quentin

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

Related Questions