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

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

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

HTML is not reading external Javascript file

I am trying to write a very simple HTML page that displays a message generated by a JS file. I am somewhat new to HTML / JS and I am certain there is something pretty simple I am missing, but I cannot for the life of me get the page to read the script. When I load the page, it is completely BLANK without any errors in the inspector.
This is the project folder structure:
-Project (folder)
--templates (folder)
----home.html
--src (folder)
----home.js
--styles (folder)
----home.css
Also, I'm pretty sure that my HTML page SEES the script, because when I remove or rename the script, I get an error in the browser's inspector telling me that it cannot find the script. So it SEES the script, it just is not running it for some reason.
Here is the code...
home.html:
<html>
<head>
<link rel="stylesheet" type="text/css" href="../styles/home.css"></link>
<script type="type/javascript" src="../src/home.js"></script>
</head>
<body>
<div id="bodytext"></div>
</body>
</html>
home.js:
(function() {
console.log("I AM READING THE SCRIPT");
document.getElementById('bodytext').innerHTML = "I AM READING THE SCRIPT";
})();
Could some generous soul out there please clue me in to what extremely simple mistake I'm making?
Thank You!
Value for type attribute should be text/javascript as follows:
<script type="text/javascript" src="../src/home.js"></script>
Your script is running before the DOM is completely done loading. If you put your <script> tag right before your closing body tag (</body>), it will run after the DOM is loaded, and you will be able to traverse the DOM like normal.
Value for type attribute should be text/javascript as follows
enter code here
ALong with this you will have to change your java script code as follows, so that script gets executed only when page is completely loaded & document object is availabe.
window.onload = function() {
console.log("I AM READING THE SCRIPT");
document.getElementById('bodytext').innerHTML = "I AM READING THE SCRIPT";
};
What worked for me was adding charset="utf-8" to my css link as well as my javascript script (for me, both did not work). Example:
<link rel="stylesheet" type="text/css" href="css/main.css" charset="utf-8"></link>
<script src="javascript/script.js" charset="utf-8"></script>

Prepare jquery before jquery and page load

I have recently discovered the new trend of including all .js script at the end of the page.
From what i have read so far seems pretty ok and doable with an exception.
The way I am working is using a template like:
<html>
<head>
<!-- tags, css's -->
</head>
<body>
<!-- header -->
<div id="wrapper">
<?php
include('pages/'.$page.'.php');
?>
</div>
<!-- footer -->
<!-- include all .js -->
</body>
</html>
Now, if I want to use this example on my page http://www.bootply.com/71401 , I would have to add the folowing code under my jquery inclusion.
$('.thumbnail').click(function(){
$('.modal-body').empty();
var title = $(this).parent('a').attr("title");
$('.modal-title').html(title);
$($(this).parents('div').html()).appendTo('.modal-body');
$('#myModal').modal({show:true});
});
But that would mean I either use that in every page - even if I do not have use for it, either generate it with php in the $page.'php' file and echoing it in the template file, after the js inclusion.
I am sure though, better methods exist and I don't want to start off by using a maybe compromised one.
Thanks!
Please avoid using inline scripts as they are not good maintainable and prevent the browser from caching them. Swap your inline scripts in external files.
Fore example you could put all your JavaScript in one file an check the presence of a specific element before initialize the whole code. E.g.:
$(document).ready(function(){
if($('.thumbnail').length) {
// your thumbnail code
}
});
A better way to execute "page specific" JavaScript is to work with a modular library like requirejs. You can modularize your scripts depending on their functionality (like thumbnails.js, gallery.js etc.) and then load the necessary script(s) depending e.g. on the existence of an element:
if($('.thumbnail').length) {
require(['ThumbnailScript'], function(ThumbnailScript){
ThumbnailScript.init();
});
}
The best way you can go is create a separate file for this code.
Let's name it app.js. Now you can include it under the jQuery inclusion.
<script type="text/javascript" src="app.js"></script>
This will prevent code repeat.
One more thing, pull all the code in $(document).ready(). Here is an example. So your app.js file will look like this:
$(document).ready(function(){
$('.thumbnail').click(function(){
$('.modal-body').empty();
var title = $(this).parent('a').attr("title");
$('.modal-title').html(title);
$($(this).parents('div').html()).appendTo('.modal-body');
$('#myModal').modal({show:true});
});
})

Conflict between jQuery.load(), jQuery.focus(), and link tags

Back-story
I am creating a web application in which individual pages are "loaded" via the jQuery .load function. Originally the loaded page was a single file, but as it got longer I decided to split it into a .html file, a .css file, and a .js file.
Strangely, a single design flaw arose surrounding an element that was positioned using percentage values within the css. To see if I modified the styling while I moved, I replace the style tag (omitting the link tag instead) and it worked fine. Back and fourth a few times and I learned it was strictly occurring only when I used link tags rather than embedding it via style tags.
I wanted to use link tags, so I tried to narrow the problem down. After a while of fiddling, I traced it down to the .js file, specifically a usage of the .focus function on $(document).ready. If I comment out the .focus, everything works fine. Uncomment, and it breaks.
This appears to only happen in Chrome. It doesn't occur in FF26 or IE11.
Example
A fiddle.
Note that the problem only occurs in Chrome and that caching must be disabled. As Chrome's temporary cache disable doesn't extend into iframes of iframes, a direct result is easier to work with.
jQuery provides a callback function when the .load() method has completed and the DOM has been updated. This is where you would want to operate on elements that have been inserted from your external url.
<script>
$(document).ready(function() {
$('#content').load('html/portal.html', function() {
//now i can operate on elements loaded from html/portal.html
//they have been inserted into the DOM
$('input#input').focus();
})
});
</script>
As far as references to the link element, if you want to dynamically load a stylesheet from an external url using javascript you can employ a javascript function something like this:
//load deferred stylesheets
function loadStyleSheet(src) {
if (document.createStyleSheet) {
document.createStyleSheet(src);
} else {
$("head").append($("<link rel='stylesheet' href='"+src+"' type='text/css' media='screen' />"));
}
}
If you want to load an external javascript file you can use jQuery.getScript():
jQuery.getScript('/js/external.js');
So putting all of this together, if you want to load some content from an external resource, insert it into the DOM and the load an external stylesheet and an external javascript resource you could do so as follows:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
//function to load a deferred stylesheets
var loadStyleSheet = function(src) {
if (document.createStyleSheet) {
document.createStyleSheet(src);
} else {
$("head").append($("<link rel='stylesheet' href='"+src+"' type='text/css' media='screen' />"));
}
}
$('#someWrapper').load('external-url.html #someWrapper > *', function() {
loadStyleSheet('/css/external.css');
jQuery.getScript('/js/external.js');
})
});
</script>
</head>
<body>
<div id="someWrapper">
<!-- external content is loaded here -->
</div>
</body>
</html>

make an unordered list into a drop down menu

If I have this code showing on Wordpress, what is the easiest way to turn this into a jump menu?
<ul class='toc-odd level-1'>
<li>It's finally here</li>
<li>Improvements</li>
<li>Handling</li>
</ul>
Can i use jquery like it showed in this thread: How to convert unordered list into nicely styled <select> dropdown using jquery?
and if so, where would i place the code examples shown in said post?
For starters, if you're new to jQuery, you might have noticed that you can create inline jQuery using script tags inside of your HTML web page, or you can create a separate .js file that is linked to your HTML file (preferred) using either a CDN (check it out here) or manually providing the script doc files yourself. I prefer using Google's CDN because they have plenty of servers that are most likely closer to the client, and the client only has to load the scripts once through the CDN.
In your HTML, provide the script tags, and then start working with JavaScript and jQuery!
<head>
<title>your webpage</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js" type="text/javascript"></script>
//BELOW IS YOUR OWN SCRIPT FILE REFERENCE!
<script src="Scripts/Jscript1.js" type="text/javascript" ></script>
Also, if you would like the jQuery IntelliSense to work in the script file, all you have to do is add a reference link in the script file you are using!
/// <reference path="jquery-1.7.1-vsdoc.js" />
$(document).ready(function () {
$('.toc-odd level-1').hover(
function () {
//show its submenu
$('ul', this).slideDown(100);
},
function () {
//hide its submenu
$('ul', this).slideUp(100);
}
);
});
The above jQuery example is just 1 way out of millions that you could implement to render your code. If you have interest in learning a fast and concise library, then check out the learn jQuery in 30 days.

Categories

Resources