Inline Javascript works but not when external - javascript

I have this short Javascript code that I want to put in a external file. The reason being is because there will be many .htm pages that would use it. So instead of putting it all inline at every single file, I want to put it in an external file.
But the thing is, it doesn't work. The script is basically a "back to top" button. It works flawlessly when I put the script in the .htm file. Another note by the way, I'm loading the .htm file in a Div, could that cause problems? Edit: The file is loaded through the .load() jQuery function.
I have also tried putting the script inline in my index.html but it fails to work there too.
Here is the code:
$('.backtotopwrapper').click(function(){
$('body,html').animate({scrollTop: "0px"},1500);
});
Update: I have tested my other .js code and the ones that have nothing to do with the .htm file work. The code that is specific to the elements inside the .htm is the only one that doesn't work.

OK, 3 files :
main.html
loremIpsum2.html
myScroll.js
1). In main.html I call jQuery and myScroll.js external files
Also I have an empty wrapper div (<div id="loader"></div>) where I put the contents of loremIpsum2.html using jQuery .load() so
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>link to external js file</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="myScroll.js"></script>
<script>
/* <![CDATA[ */
$(document).ready(function() {
$("#loader").load("loremIpsum2.html");
}); // ready​​​
/* ]]> */
</script>
</head>
<body>
<div id="wrap">
<div id="loader"></div>
</div><!--wrap-->
</body>
</html>
2). In loremIpsum2.html, I have just a bunch of paragraphs but at the end I have my button :
<a class="backtotopwrapper" href="javascript:;">go to top</a>
3). In myScroll.js i Have the function for my scrolling button :
$(function () {
$('body').on("click", ".backtotopwrapper", function () {
$('body,html').animate({
scrollTop: 0
}, 1500);
});
});
Since I am loading the file where the button is via .load(), I am using .on() in its delegated form.
See DEMO and feel free to explore the source code.
NOTE : .on() requires jQuery v1.7+

I had the same problem but didn't perform any solution mentioned here, i actually dicovered what made it work for me when my external scripts werent working but the same code works internally.
Just remove any spaces/special characters from your external script filename e.g instead of calling it "admin-script.js", call it "adminscript.js", without the special characters like the hyphen, then refer to the script with the new name and thats it, it worked for me.

Related

jquery not working inside of html script tags

This question is not a duplicate!
I have tried many methods, yet they havent worked. I cannot tell what i am doing wrong. I have the src in the top script tags and i used $(document).ready
Here is the code:
<html>
<head>
<script src="jquery-3.3.1.min.js"></script>
</head>
<button id="button">Button</button>
<script>
$(document).ready(function() {
$("#button").click(function() {
alert("Test");
});
});
</script>
</html>
Does the file jquery-3.3.1.min.js exist in the same path as your html file?
If not, you need to download jQuery or link to a CDN instead of a local file.
Your "jquery-3.3.1.min.js" file may not present in your working path. Make sure you provided the correct path or else you can load jquery from CDN directly.
Or
Try moving the script inside 'head' tag.

Javascript(Jquery) executes in HTML header but not not when in an external JS file

I know this stuff has been asked before...but I am a bit confused about this still. I have my index.html file and I have a script tag linking to my external JS file. If I only have that script tag the JS does nothing, but if I copy the JS and paste it into it's own script tag in the HTML header it works just fine. There's gotta be something I'm missing with Jquery.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="jquery-3.2.0.js"></script>
<link rel="stylesheet" href="FinalProjectCss.css">
<title>Dustin Naylor - Final Project</title>
<script src="FinalProjectJS.js"></script>
<script>
$(document).ready(function(){
$(".section").click(function(){
if($(this).next().is(":hidden")) {
$(this).next().slideDown("fast");
} else{
$(this).next().hide();
}
});
});
</script>
</head>
<body>
<span class="section">Click Me</span>
<div class = "hiddenDiv">
Oh hey there.
</div>
</body>
</html>
So the code in the last script tag that is Jquery stuff is exactly copied into a separate JS file named FinalProjectJS.js. In the current state this code is in it works as desired, but when I remove that chunk of code from the html file it doesn't work....Sorry for my nubishness, I'm rather new and any help would be great! thanks!
Can you write the contents of your jquery file: FinalProjectJS.js? The syntax for calling the external file seems to be correct. So I'm thinking it might be something about the path or the jquery external file contents itself. Make sure you don't include <script> tags on that file. Here's a sample.
Another thing, last time I've worked with jquery, I can't directly see it take effect when both my files are stored locally. It had to be stored in a server first, then accessed by my PC. Only then did my jquery took effect. A dev I worked with added some text to my Google Chrome's properties (target) so that even if my file is not stored in a server, I can see jquery take effect even if both my HTML and jquery files are stored locally.
...sorry, I'm not allowed to comment yet to clarify your post.
You must add the jQuery script tag before FinalProjectJS.js for the jQuery snippet to work.
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous">

how to make an ajax call with jquery loaded in the body section not head section

I have a layout file where i included Jquery just before closing tag.
//layout.handlebars
<!DOCTYPE html>
<html>
<head></head>
<body>
{{{body}}} // renders the body content
<script src='/js/jquery-2.2.4.min.js'></script>
</body>
</html>
I also have a page specific javascript(helper.js) that makes an Ajax call.
<div>Some sample data</div>
<script src="/js/helper.js"></script>
but the problem here is jquery is loaded at the end of the page but i am referring to it in the external javascript before jquery is loaded. which shows me '$' is not defined and i know that is obvious.
One solution to this will be like adding jquery to the head section but that is not what i want.
Is there any approach that i can apply to make an ajax call from external file without moving Jquery to head section.
Any help is much appreciated!!
Is there any approach that i can apply to make an ajax call from external file without moving Jquery to head section.
Yes, I assume you already understand the cause of the issue. As you see below the final content is ..
<!DOCTYPE html>
<html>
<head></head>
<body>
<div>Some sample data</div>
<script src="/js/helper.js"></script> <!--Jquery is not loaded yet, and hence $ is undefined -->
<script src='/js/jquery-2.2.4.min.js'></script>
</body>
</html>
As you already know one option is to move jquery anywhere in the HTML but make sure its loaded before any other jquery dependent files. Now since you don't want to take this option. we have another option.
Solution:
Our only aim is to make sure the jquery library is loaded prior to any other jquery dependent files.
We can get the files on document.ready using $.getScript()
$(function(){
$.getScript( "/js/helper.js", function( data, textStatus, jqxhr ) {
console.log( "Load was performed." );
});
});
Extras: If you feel this is a overhead and you cannot add this code to all the files in your page (since there can be too many files ), You can write a generic function and a global array variable , This function will check for file paths in the array and execute each one synchronously and remove from the array. Make sure this generic function is called in every document.ready event.
One Solution is that You can put the jquery script at the start of body tag before {{{body}}} section .. In this way your helper script will be rendered after jquery and your problem will be solved .....
Well its not pretty but you could use some kind of test and wait loop something like
<script>
(function test(){
if( window.jQuery ){
//your jQuery code
} else {
setTimeout(function(){ test(); }, 200);
}
})
</script>

jQuery's include method doesn't work

As my website has only one page, and the index.html was getting really long and impossible to read. So I decided to put each section in a different HTML file and use jQuery to included it.
I used jQuery's include in the way as it has been mentioned here to include a external HTML file but apparently it doesn't work for my website. I really don't know what is the problem.
Here is the link of my workspace.
Here is what I am doing in index.html file to include other sections
<script src="./js/jquery-1.11.1.min"></script>
<script>
$(function() {
$("#includedContent").load("./page1.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page2.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page3.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page4.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page5.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page6.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page7.html");
});
</script>
I also used this method to make sure the file is accessible and everything was fine. So the problem is not the accessibility of the files
You are overwriting the contents of #includedContent seven times (see documentation of jQuery.load). With AJAX, there is no guarantee which request will complete first so you will end up with random page content inside the container.
The solution is to create containers for each page and load each page inside its dedicated container, something like this:
<div id="includedContent">
<div class="page1"></div>
<div class="page2"></div>
<div class="page3"></div>
</div>
$(document).ready(function() {
$("#includedContent .page1").load("page1.html");
$("#includedContent .page2").load("page2.html");
$("#includedContent .page3").load("page3.html");
});
NB: Having said all that, I do not understand how AJAX solves the problem of the page being too long/impossible to read.
There are several things that look odd to me:
all your load functions run at document ready, which is weird while having all the same target. load replaces (not adds) the content of the selected element with what is being loaded, you probably are trying to add all the html contents, but your current setup would actually just load page7.html into #includedContent
the paths look strange to me, i guess ./ may cause errors, try to leave out ./ everywhere.
rather than loading an entire html page, you might just want to load a piece of that file (i dont know how pageX.html looks), for example you would not want to load the <html> node entirely, rather the content only: .load('page1.html #content')
are you including jquery correctly? there is no .js in your inclusion

Sometimes jQuery plugin is not loaded

I am using jQuery a lot, but sometimes I get stuck because my browser cannot see the jQuery library, or maybe loads the library after running the my JavaScript code.
Pseudo-code to explain my question:
<html>
<head>
I always load CSS here
I always load jquery here
</head>
<body>
<p class="link-style3"><span id="my_tag"><span>Bize Hemen Yazın</span></span></p>
<script>
$(function() {
$('#my_tag').click(function(e) {
alert('tesrt');
});
});
</script>
</body>
</html>
I always put my stuff in the order like below, but this doesn't work now. When I click the <span id="my_tag">, it doesn't do anything, and doesn't return any error.
what should I do?
Here is the entire code jsfiddle
Try to avoid some syntax errors like(suggestable only)
<script type="text/javascript">
$(function() {
$('#my_tag').click(function() {
alert('tesrt');
});
})
</script>
and put your code at the top after you load the js files
A few things you can do:
inspect your document (network pane in devtools) to see if everything
is loading correctly
Move your scripts to the bottom of the page
use $(document).ready(function(){ ... });

Categories

Resources