When I use this code inside my HTML document it's working:
$('a.tocenter[href*=#]').click( function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {
var $target = $(this.hash);
$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
if ($target.length) {
var targetOffset = $target.offset().top;
$('html,body').animate({ scrollTop: targetOffset - ( $(window).height() - $target.outerHeight(true) ) / 2 }, 1000);
return false;}
}
});
If I try to put this code inside an external JavaScript file and then link it with:
<script src="js/main.js"></script>
It's not working, to let it work I had to wrap it inside:
$( window ).load(function() {
...
});
If I do this it works.
I'm a total newbie in JavaScript/jQuery, is this normal or am I doing something wrong? Why is it behaving like that? Is it a good practice to do that?
The only purpose of having it in an external file is for keeping the code clean and understandable.
“external javascript file not working” Code Answer's Most likely, the problem is that you are including your js file in a head tag or somewhere above your main content. ... You should be able to add the js file in a script tag. The page loads first then JavaScript.
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.
You should put all javascript code in a <script> tag for the browser to recognize and make it run and for the src attribute of the script tag to find your 'script. js' file, it just has to be in the same directory as the html file, you don't need to specify the entire file root.
Placing scripts in external files has some advantages: It separates HTML and code. It makes HTML and JavaScript easier to read and maintain. Cached JavaScript files can speed up page loads.
You're attaching an event handler to an element using .click()
, so it needs to be there at this point.
This can be guaranteed if you check for the page ready
:
$(function() {
// your code
});
or window load
:
$(window).load(function() {
// your code
});
, or if you keep the script in the page, at its end:
<script type="text/javascript">
// your code
</script>
</body>
Another way is to use delegation
:
$(selector_for_element_that_will_surely_be_there).on(event, selector_for_element_receiving_the_event, function() {
// your code
});
// ie:
$(document).on('click', 'a.tocenter[href*=#]', function() {
// your code
});
Have a look about it: http://api.jquery.com/on/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With