1

I am trying to use Jquery in a separate .JS file since keeping all JavaScript code out of the HTML document will increase the performance of loading the HTML document.

For this example I am using "index.html" and "main.js"

Below is index.html:

    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>append demo</title>

      <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
      <script src="testJS/main.js"></script>

    </head>
    <body>

    <p>I would like to say: </p>


<!-- CODE BELOW MUST BE REMOVED FROM THIS DOCUMENT -->
    <script>
    $( "p" ).append( "<strong>Hello</strong>" );
    </script>

    </body>
    </html>

I would like to cut the code from the html and insert it into main.js however the example below did not work for me:

main.js:

p.append( "<strong>Hello</strong>" );

I've also tried this with no success:

 $( "p" ).append( "<strong>Hello</strong>" );

How could I fix this and what is the difference between having JavaScript inside and having it inside a .js file?

4 Answers 4

2

I would suggest the use of the $( document ).ready() function that JQuery provides something like this:

$(document).ready(function() {
    $("p").append( "<strong>Hello</strong>" );
});

Here you can find more info: http://learn.jquery.com/using-jquery-core/document-ready/

Sign up to request clarification or add additional context in comments.

Comments

2

You need to add the code in dom ready handler, because other wise when the code is executed the p element is still not added to the dom - it is because since the main.js is added before the p element in your markup, but anyway the safest option is to use dom ready handler for dom manipulation

jQuery(function($){
    $( "p" ).append( "<strong>Hello</strong>" );
})

Comments

1

When using external js you must wrap your code in document ready function like this

$(function(){
  $('p').append('<strong>Hello</strong>');
});

*Note - $(function(){ is shorthand for $(document).ready(function(){

Comments

0

As explained by Arun P Johny, the problem is that the js code is executing before the DOM elements it depends on are ready.

Another solution is to change your external file so that it defines a function, which you would then call at the end of the body in your html file.

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>append demo</title>

  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="testJS/main.js"></script>

</head>
<body>

<p>I would like to say: </p>

<script>
  writeText();
</script>
</body>
</html>


<!-- main.js -->

function writeText(){
  $( "p" ).append( "<strong>Hello</strong>" );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.