Using jQuery accordion from an external JS file - javascript

I have a standard jQuery accordion which works fine. I want to reuse this in a lot of HTML files and it would be cleaner to have the JS in a file rather than have to repeat in a script tag in each HTML file.
My HTML header is:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.6.0.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js" type="text/javascript"></script>
<script src="test.js" type="text/javascript"></script>
</head>
My test.js file is:
$(function() {
$("#accordion").accordion({
heightStyle: "content",
header: "h4"
})
});
The accordion does not work for me when moved to test.js. When I try it in a playground I get: '$' is not defined.
I know $ is a shortcut for document.getElementById(). It was suggested to wrap the JS inside an Immediately Invoked Function Expression where the IIFE takes jQuery as an argument and assigns it to $ within its scope, ensuring that $ is defined:
(function($) {
$(function() {
$("#accordion").accordion({
heightStyle: "content",
header: "h4"
});
});
})(jQuery);
However, trying this in the playground leads to a jQuery not defined error. I have jQuery included before test.js as shown above so I am unsure why I am getting this error?
So, I am wondering how to get past this error and get the jQuery accordion working when the code is in a javascript file?
Incidentally, it seems like every HTML file that uses the accordion will need jQuery and jQuery-ui included as well as test.js. It seems like there is no way to move the jQuery files to be in test.js only.

Related

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">

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

I found few answers on stack overflow but still cant resolve my problem.
I am running on Django but I dont think it is relevant for this error.
I try to make work my date picker java script but I am getting the error
1:27 Uncaught TypeError: $(...).datepicker is not a function(anonymous function) # 1:27fire # jquery-1.9.1.js:1037self.fireWith # jquery-1.9.1.js:1148jQuery.extend.ready # jquery-1.9.1.js:433completed # jquery-1.9.1.js:103
jquery-2.1.0.min.js:4 XHR finished loading: POST "https://localhost:26143/skypectoc/v1/pnr/parse".l.cors.a.crossDomain.send # jquery-2.1.0.min.js:4o.extend.ajax # jquery-2.1.0.min.js:4PNR.findNumbers # pnr.js:43parseContent # contentscript.js:385processMutatedElements # contentscript.js:322
This is all my scripts :
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.dateinput').datepicker({ format: "yyyy/mm/dd" });
});
</script>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
<script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>
<!-- Just to make our placeholder images work. Don't actually copy the next line! -->
<script src="http://getbootstrap.com/assets/js/vendor/holder.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="http://getbootstrap.com/assets/js/ie10-viewport-bug-workaround.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#extra-content").hide();
$("#toggle-content").click(function(){
$("#extra-content").toggle();
});
});
</script>
any feedback will be very appreciated
What went wrong?
When you include jQuery the first time:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
The second script plugs itself into jQuery, and "adds" $(...).datepicker.
But then you are including jQuery once again:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
It undoes the plugging in and therefore $(...).datepicker becomes undefined.
Although the first $(document).ready block appears before that, the anonymous callback function body is not executed until all scripts are loaded, and by then $(...) (window.$ to be precise) is referring to the most recently loaded jQuery.
You would not run into this if you called $('.dateinput').datepicker immediately rather than in $(document).ready callback, but then you'd need to make sure that the target element (with class dateinput) is already in the document before the script, and it's generally advised to use the ready callback.
Solution
If you want to use datepicker from jquery-ui, it would probably make most sense to include the jquery-ui script after bootstrap. jquery-ui 1.11.4 is compatible with jquery 1.6+ so it will work fine.
Alternatively (in particular if you are not using jquery-ui for anything else), you could try bootstrap-datepicker.
The error is because you are including the script links at two places which will do the override and re-initialization of date-picker
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.dateinput').datepicker({ format: "yyyy/mm/dd" });
});
</script>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
So exclude either src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"
or
src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"
It will work..
if you are using ASP.NET MVC
Open the layout file "_Layout.cshtml" or your custom one
At the part of the code you see, as below:
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
#Scripts.Render("~/bundles/jquery")
Remove the line "#Scripts.Render("~/bundles/jquery")"
(at the part of the code you see) past as the latest line, as below:
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
This help me and hope helps you as well.
You just need to add three file and two css links. You can either cdn's as well.
Links for the js files and css files are as such :-
jQuery.dataTables.min.js
dataTables.bootstrap.min.js
dataTables.bootstrap.min.css
bootstrap-datepicker.css
bootstrap-datepicker.js
They are valid if you are using bootstrap in your project.
I hope this will help you.
Regards,
Vivek Singla
Including more than one reference to Jquery library is the reason for the error Only Include one reference to the Jquery library and that will resolve the issue
We need to add the declaration of our jQuery plugin under interface with the same name. We don’t want to mess with the jQuery source code, so we need to create our own type definition file. I’m using React/typescript so just follow these steps
Open nodemodules and go into types folder.
Go into jQuery and open jQuery.d.ts fileand add the below code into interface JQuery<TElement = HTMLElement> extends Iterable {
daterangepicker(options?: any, callback?: Function) : any;
I’m declaring the daterangepicker function (this is the actual function that the API expose) and setting all its arguments as any ( You can go further and use specific types, but in this case, I will keep it simple ).
Now when the typescript compiler sees our interface, it will merge it with the jQuery interface and the error is gone.
That’s all!
This error is occur,because the function is not defined.
In my case i have called the datepicker function without including the datepicker js file that time I got this error.

How do I include jQuery code in my node.js web app?

so I've been working on a (fairly simple) RESTful app using node.js, and I've made it towards the very last bit, now the only bit missing is using jQuery to manipulate the html page so I can edit the content of the html - and it's driving me absolutely mad.
I took the try.jquery.com tutorial, and it was pretty smooth; I'd by no means call myself a master of jquery, but I have very little trouble writing the code for basic html manipulation, except I never really considered where the jquery code would go. I've tried a bunch of different stuff and only one (really inconvenient) way has worked, so I was wondering if I could get some clarification.
(Note: all the js files are in the root folder, and index.html is in root/public; and I'm basically just running app.js through npm/package.json)
I've tried including the jQuery code in the main app.js file:
app.js
//some imports/requires here
var $ = require('jquery');
//more imports/requires here
//error; document is undefined
$(document).ready($('h1').text('Im Here');
app.get('/', function (req, res) {
res.sendFile(__dirname+'/public/index.html');
});
index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<title>Inspiratorator</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script="../app.js"></script>
I've tried including the jQuery code in its own file (tried just letting the code sit in the js file, and tried exporting the code as a function and calling it from app.js - both did nothing):
jusQueryin.js
var $ = require('jQuery'); //tried with and without this
$(document).ready(function () {
$(' button ').on( 'click', $('h1').text("I'm here") );
console.log('kpa');
});
index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<title>Inspiratorator</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script="../jusQueryin.js"></script>
I've also tried (this worked, but I don't know how I would deal with the code in here from other .js file, if it is possible):
index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<title>Inspiratorator</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script>
$(document).ready(function () {
$(' button ').on( 'click', $('h1').text("I'm here") );
console.log('kpa');
});
</script>
I've also tried different variations(i.e. including the 2nd part of the ready function in a function (or not), using an onClick event inside the dom.ready function, etc..), but the only one that worked was the last approach
Ideally, I'd like to be able to use the jQuery code inside app.js, less ideally would be in its own file; or if I have to include it inside the html file for some reason, I would at least need to be able to communicate with the code in the script block so that I can give it info from the database and so on.
Remeber one thing jQuery needs a window object to work. The first functionality of jquery is as dom query, dom is within a window object. As a result you must load the jquery and attach it to a window object.
As a node app you will have a browser window as a view to your app. Try adding jquery to that window from a CDN, add your requires there, voila the containing scope(window) which contains jquery now as global passes it also to the newly required file.
Error: jQuery requires a window with a document
index.html
<script>
window.$ = window.jQuery = require('./node_modules/jquery');
</script>
<script>
var UI = require('./controllers/UI');
UI.init(window);
</script>
Now var UI, which is a module in my case, contains

Inline Javascript works but not when external

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.

merge jquery-1.9.1.min.js and query.mobile-1.3.0.min.js in a single file give error

I'm developing a jquery mobile webapp
The base structure require jquery.js and jquery-mobile.js ad documented in jqueryMobile doc.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="myjqueryconfig.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
</head>
All works good with this structure but I want to merge jquery js file with jquery-mobile js file to have a single js file but when I do that (simply by cut and pust jquery mobile code to the end of jquery file) page stop working and firebug give me a javascript error:
TypeError: $(...).bind(...) is not a function
My single .js file is structured as:
//jquery 1.9.1 min source code
$(document).bind("mobileinit", function(){
$.mobile.autoInitializePage = false
})
//jquery mobile min 1.3.0 source code
Adding a ; between the files when concatenating them solves the problem.
Look at this code :
(function(){
console.log('A');
}())
(function(){
console.log('B');
}())
Without an intermediary semicolon, the second IIFE looks like an argument passed to the first one. And so it fails. Adding the semicolon solves the problem as it specifies those are two statements.
Semicolons in JavaScript are optional but it's very dangerous to omit them.

Categories

Resources