Soeb Safi
Soeb Safi

Reputation: 341

js code is not working in an external file, but works file when placed in the same html page

I have this code in the footer of my html page

<script type="text/javascript">
// using jQuery
$('video,audio').mediaelementplayer();
</script>

the above code is adding video player on the html page.

Now I have created a separate js file in which I have already have some line of code which is creating owl sliders, tooltips, number counters etc.

When I add the above code into that separate js file it does not work, instead when I keep it in the footer of the html page it works fine.

Upvotes: 1

Views: 8608

Answers (5)

Brett Gregson
Brett Gregson

Reputation: 5913

Try placing your code within $(function(){ ... }. This will execute when the DOM is loaded (currently your code is being executed before jQuery is loaded, if you check the JavaScript console, you will see an error something like $ is not defined)

 $(function(){
     $('video,audio').mediaelementplayer();
 });

or

 $( document ).ready(function() {
     $('video,audio').mediaelementplayer();
 });

You can read about what that is doing here. $(function() is the same as $( document ).ready()

Upvotes: 2

Erick Jimenez
Erick Jimenez

Reputation: 368

You may wait until jQuery is full loaded or ready.

Ex.

$(document).ready(function($) {
    // Your code goes here
    $('video,audio').mediaelementplayer();
});

This code goes in external js file, then you need to include the file in the HTML

<script type="text/javascript" src="path/to/your/js/file"></script>

Upvotes: 0

nabilinfo
nabilinfo

Reputation: 49

How do you call your external js file ?
You must add your references js before your external js file.
you must add your function on document.ready.

Upvotes: 0

Rene Limon
Rene Limon

Reputation: 624

your html(basically) should look like this:

<html>
  <head>
  </head>
  <body>
     <!-- html code here -->

     <!-- add jquery lib -->
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
     <!-- your script -->
     <script src="you/file/path.js"></script>
  </body>
</html>

and your jquery file:

jQuery(function($) {
    // your functions here
    $('video,audio').mediaelementplayer();
});

Upvotes: 1

Nolan Zandi
Nolan Zandi

Reputation: 111

Do you have a proper link to the separate js file in your page, generally at the bottom of the body? It should look something like this:

<script type="text/javascript" src="/joyride_odoo_models/static/js/scripts.js"/>

If you've done that properly, have you tried clearing your browser cache? You may need to do that to detect new javascript files.

Upvotes: 0

Related Questions