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.
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.
-
If you place the reference to the external file in the
head
of the page you need to use a document.ready handler: ie$(function() { /* your code here... */ });
– Rory McCrossan Commented Jul 14, 2016 at 14:59 - could you share us the full file? – Adam Commented Jul 14, 2016 at 15:08
5 Answers
Reset to default 2Try 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()
your html(basically) should look like this:
<html>
<head>
</head>
<body>
<!-- html code here -->
<!-- add jquery lib -->
<script src="https://ajax.googleapis./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();
});
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.
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.
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>