Javascript notes - libraries and frameworks: Difference between revisions

From Helpful
Jump to navigation Jump to search
mNo edit summary
 
Line 1,196: Line 1,196:


To get a feel of what jQuery code looks like:
To get a feel of what jQuery code looks like:
<code lang="javascript">
<syntaxhighlight lang="javascript">
// select all nodes with class 'headerclass', make it red bold text
// select all nodes with class 'headerclass', make it red bold text
$('.headerclass').css({color:"#993300", fontWeight:"bold"})
$('.headerclass').css({color:"#993300", fontWeight:"bold"})
</code>
</syntaxhighlight >
<code lang="javascript">
<syntaxhighlight lang="javascript">
// add an outline to every element on the page:
// add an outline to every element on the page:
$('*').css('outline','1px solid red')
$('*').css('outline','1px solid red')
</code>
</syntaxhighlight >


{{comment|(not that you would typically add style this way)}}
{{comment|(not that you would typically add style this way)}}
Line 1,212: Line 1,212:


...often the ''same'' selection, so that you can easily make multiuple alterations, e.g.
...often the ''same'' selection, so that you can easily make multiuple alterations, e.g.
<code lang="javascript">
<syntaxhighlight lang="javascript">
// This means you can chain multiple alterations like:
// This means you can chain multiple alterations like:
$('.headerclass').css({color:"#993300", fontWeight:"bold"}).addClass('highlight');
$('.headerclass').css({color:"#993300", fontWeight:"bold"}).addClass('highlight');
</code>
</syntaxhighlight >




...or other selections when it makes sense, e.g. for navigation functions:
...or other selections when it makes sense, e.g. for navigation functions:
<code lang="javascript">
<syntaxhighlight lang="javascript">
// Basic example:
// Basic example:
//  Select all 'img' nodes, show a red outline;
//  Select all 'img' nodes, show a red outline;
//  then make a new selection of all parents (of all imgs), and show a blue outline on them:
//  then make a new selection of all parents (of all imgs), and show a blue outline on them:
$('img').css('outline','1px solid red').parents().css('outline','1px solid blue');
$('img').css('outline','1px solid red').parents().css('outline','1px solid blue');
</code>
</syntaxhighlight >


<code lang="javascript">
<syntaxhighlight lang="javascript">
// More complex example:
// More complex example:
//  Find each h2 element with the 'title' class,
//  Find each h2 element with the 'title' class,
//  and when clicked, toggle the visibility of the div sibling after it
//  and when clicked, toggle the visibility of the div sibling after it
$('h2.title').click(function(){ $(this).next('div').toggle() })
$('h2.title').click(function(){ $(this).next('div').toggle() })
</code>
</syntaxhighlight >






Functions may do other things (than altering the page or the selection), such as...
Functions may do other things (than altering the page or the selection), such as...
<code lang="javascript">
<syntaxhighlight lang="javascript">
// - things that apply to the whole set:
// - things that apply to the whole set:
alert( 'There are '+$("img").size()+' images on this page' );
alert( 'There are '+$("img").size()+' images on this page' );
</code>
</syntaxhighlight >


<code lang="javascript">
<syntaxhighlight lang="javascript">
// ...per-node event function registration  (doesn't change the selection)
// ...per-node event function registration  (doesn't change the selection)
$('#tags span').click(  function(){alert('I am now clickable');}  )
$('#tags span').click(  function(){alert('I am now clickable');}  )
</code>
</syntaxhighlight >


<code lang="javascript">
<syntaxhighlight lang="javascript">
// ...triggering registered events          (doesn't change the selection)
// ...triggering registered events          (doesn't change the selection)
$('#tags span').click()
$('#tags span').click()
</code>
</syntaxhighlight >


<code lang="javascript">
<syntaxhighlight lang="javascript">
// ...get contents -- often operate only on the first element
// ...get contents -- often operate only on the first element
$("div").html();
$("div").html();
//  ...if you want some logic for each of these elements, you can use $.each (see below)
//  ...if you want some logic for each of these elements, you can use $.each (see below)
</code>
</syntaxhighlight >




Line 1,263: Line 1,263:
* <tt>'''html()'''</tt> {{comment|(one of the [http://api.jquery.com/category/manipulation/ manipulation] functions)}} is DOM-to-strings without arguments,  and strings-to-DOM when you do give arguments
* <tt>'''html()'''</tt> {{comment|(one of the [http://api.jquery.com/category/manipulation/ manipulation] functions)}} is DOM-to-strings without arguments,  and strings-to-DOM when you do give arguments


<code lang="javascript">
<syntaxhighlight lang="javascript">
// For example: copy the page title into the page (which is not really page content but you can still get it via html())  
// For example: copy the page title into the page (which is not really page content but you can still get it via html())  
$('body').append( '<div id="foo"><b>' +$('title').html()+ '</b><br/></div>' );  //the html() there is a getter (no arguments)
$('body').append( '<div id="foo"><b>' +$('title').html()+ '</b><br/></div>' );  //the html() there is a getter (no arguments)
</code>
</syntaxhighlight >






* '''val()''' [http://api.jquery.com/val/], mostly used to get form values, e.g.  
* '''val()''' [http://api.jquery.com/val/], mostly used to get form values, e.g.  
<code lang="javascript">
<syntaxhighlight lang="javascript">
// get
// get
$('#searchfield').val();
$('#searchfield').val();
Line 1,282: Line 1,282:


* <tt>'''attr()'''</tt> (get or set node attributes)
* <tt>'''attr()'''</tt> (get or set node attributes)
<code lang="javascript">
<syntaxhighlight lang="javascript">
//get parent node's DOM id:
//get parent node's DOM id:
$(this).parent.attr('id');
$(this).parent.attr('id');
Line 1,288: Line 1,288:
//set parent node's title attribute:
//set parent node's title attribute:
$(this).parent.attr('title','forks!');
$(this).parent.attr('title','forks!');
</code>
</syntaxhighlight >


Note: <tt>class</tt> is a space-separated token list, so you often want to use <tt>.addClass()</tt> and <tt>.removeClass()</tt> instead of setting class via <tt>attr()</tt>
Note: <tt>class</tt> is a space-separated token list, so you often want to use <tt>.addClass()</tt> and <tt>.removeClass()</tt> instead of setting class via <tt>attr()</tt>




<code lang="javascript">
<syntaxhighlight lang="javascript">
// Or, say, outlines on everything on the page, with random colors
// Or, say, outlines on everything on the page, with random colors
function randomcolor(){ return '#'+
function randomcolor(){ return '#'+
Line 1,305: Line 1,305:
// Note that $('*').css('outline','1px solid '+randomcolor());}) is valid code,
// Note that $('*').css('outline','1px solid '+randomcolor());}) is valid code,
//  would executes randomcolor() once so would color everything the same.
//  would executes randomcolor() once so would color everything the same.
</code>
</syntaxhighlight >






<code lang="javascript">
<syntaxhighlight lang="javascript">
// You ''could'' store a selection into a variable:
// You ''could'' store a selection into a variable:
var jqselection = $('.headerclass');
var jqselection = $('.headerclass');
// ...but this is generally only necessary when chaining functions can't express what you want
// ...but this is generally only necessary when chaining functions can't express what you want
</code>
</syntaxhighlight >




Line 1,319: Line 1,319:


And for something superfluous:
And for something superfluous:
<code lang="javascript">
<syntaxhighlight lang="javascript">
// When you hover thr mouse over a paragraph, shift the text right 30px over a second. When the mouse leaves, put it back in 0.2 seconds.
// When you hover thr mouse over a paragraph, shift the text right 30px over a second. When the mouse leaves, put it back in 0.2 seconds.
$('p').hover(
$('p').hover(
Line 1,325: Line 1,325:
   function () { $(this).animate( {marginLeft:"0px"},  200 );  }
   function () { $(this).animate( {marginLeft:"0px"},  200 );  }
);
);
</code>
</syntaxhighlight >




Line 1,448: Line 1,448:


Example of binding: Make the paragraph you click larger than all others others - and, oh, yellow.  
Example of binding: Make the paragraph you click larger than all others others - and, oh, yellow.  
<code lang="javascript">
<syntaxhighlight lang="javascript">
  $('p').click(function() {  
  $('p').click(function() {  
     $('p').css('font-size','100%').css('background-color','transparent');
     $('p').css('font-size','100%').css('background-color','transparent');
   $(this).css('font-size','120%').css('background-color','#ffa');  
   $(this).css('font-size','120%').css('background-color','#ffa');  
  });
  });
</code>
</syntaxhighlight >
Notes:
Notes:
* adds as many click handlers as there are <tt>p</tt> tags.
* adds as many click handlers as there are <tt>p</tt> tags.
Line 1,472: Line 1,472:
These work on more primitive data instead of element lists:
These work on more primitive data instead of element lists:
* <tt>$.each(''o'',''f'')</tt> can iterate over objects, arrays,and hashes, so you can do:
* <tt>$.each(''o'',''f'')</tt> can iterate over objects, arrays,and hashes, so you can do:
<code lang="javascript">
<syntaxhighlight lang="javascript">
h={'a':2,3:'d'};
h={'a':2,3:'d'};
a=[5,6,7,8];
a=[5,6,7,8];
$.each( h, function(i) { alert('['+i+']: '+this); } )
$.each( h, function(i) { alert('['+i+']: '+this); } )
$.each( a, function(i) { alert('['+i+']: '+this); } )
$.each( a, function(i) { alert('['+i+']: '+this); } )
</code>
</syntaxhighlight >
* <tt>$.grep(''a'',''f''[,''b''])</tt> arrays (filtering) {{comment|(can be positive and negative filter, see third argument)}}
* <tt>$.grep(''a'',''f''[,''b''])</tt> arrays (filtering) {{comment|(can be positive and negative filter, see third argument)}}


Line 1,617: Line 1,617:


Overriding defaults can be done by setting values in <tt>$.fn.cluetip.defaults</tt>, for example:
Overriding defaults can be done by setting values in <tt>$.fn.cluetip.defaults</tt>, for example:
<code lang="javascript">
<syntaxhighlight lang="javascript">
var _qtd = $.fn.cluetip.defaults;
var _qtd = $.fn.cluetip.defaults;
_qtd['local']=true;
_qtd['local']=true;
Line 1,625: Line 1,625:
_qtd['closePosition']='title'; _qtd['closeText']='<img src="img/x.png" alt="close"/>';
_qtd['closePosition']='title'; _qtd['closeText']='<img src="img/x.png" alt="close"/>';
_qtd['cluezIndex']=1101;
_qtd['cluezIndex']=1101;
</code>
</syntaxhighlight >




Line 1,641: Line 1,641:
===jEditable===
===jEditable===
The last editable code I used looked something like:
The last editable code I used looked something like:
<code lang="javascript">
<syntaxhighlight lang="javascript">
$('.editable').mouseover(  
$('.editable').mouseover(  
     function(){$(this).addClass('hover')}  
     function(){$(this).addClass('hover')}  
Line 1,655: Line 1,655:
               }
               }
);
);
</code>
</syntaxhighlight >


Notes:
Notes:
* The mouseovered class is there for highlighting, a visual cue about what you can click to edit, for example:
* The mouseovered class is there for highlighting, a visual cue about what you can click to edit, for example:
<code lang="css">
<syntaxhighlight lang="css">
.editable      { background:#fffff8; border:1px solid #ccc; }
.editable      { background:#fffff8; border:1px solid #ccc; }
.editable.hover { background:#ffffaa; }
.editable.hover { background:#ffffaa; }
</code>
</syntaxhighlight >


* An area is only clickable if it has a background color rather than the default <tt>transparent</tt>, so make sure it has a color set.
* An area is only clickable if it has a background color rather than the default <tt>transparent</tt>, so make sure it has a color set.
Line 1,692: Line 1,692:


In the doc's onload, you have to register a function that takes a hash value and does whatever needs to happen to the page:
In the doc's onload, you have to register a function that takes a hash value and does whatever needs to happen to the page:
<code lang="javascript">
<syntaxhighlight lang="javascript">
$.history.init(loader_callback);
$.history.init(loader_callback);
</code>
</syntaxhighlight >


The [http://plugins.jquery.com/project/history given example] also adds code to replace regular &lt;a href="#thing"&gt; style links with replacement onclick handlers {{comment|<nowiki>(using rel="history"; a class may be simpler/cleaner)</nowiki>}} that call whatever centralized #-based reload function you've written. In some cases this allows you to add some graceful degradation, but if you're going for full-on scripting, you may wan to use <tt>$.history.load</tt> directly.
The [http://plugins.jquery.com/project/history given example] also adds code to replace regular &lt;a href="#thing"&gt; style links with replacement onclick handlers {{comment|<nowiki>(using rel="history"; a class may be simpler/cleaner)</nowiki>}} that call whatever centralized #-based reload function you've written. In some cases this allows you to add some graceful degradation, but if you're going for full-on scripting, you may wan to use <tt>$.history.load</tt> directly.
Line 1,702: Line 1,702:


By default the text goes into a h3. The plugin optionally splits into a h3 and a p, but that's extra work at HTML generation time, so I chose to strip the h3's major formatting with something like:  
By default the text goes into a h3. The plugin optionally splits into a h3 and a p, but that's extra work at HTML generation time, so I chose to strip the h3's major formatting with something like:  
<code lang="css">
<syntaxhighlight lang="css">
#tooltip h3 {  
#tooltip h3 {  
     font-size: medium;   
     font-size: medium;   
Line 1,716: Line 1,716:
     opacity:0.95;-moz-opacity:0.95; filter:alpha(opacity=95);
     opacity:0.95;-moz-opacity:0.95; filter:alpha(opacity=95);
}
}
</code>
</syntaxhighlight >
It means the following is enough for a page:  
It means the following is enough for a page:  
<code lang="javascript">
<syntaxhighlight lang="javascript">
  $('[@title]').Tooltip({showURL:false,delay:0});
  $('[@title]').Tooltip({showURL:false,delay:0});
</code>
</syntaxhighlight >


-->
-->

Latest revision as of 17:53, 11 September 2023

Related to web development, lower level hosting, and such: (See also the webdev category)

Lower levels


Server stuff:


Higher levels



Some shared concepts

Web components

This article/section is a stub — some half-sorted notes, not necessarily checked, not necessarily correct. Feel free to ignore, or tell me about it.


Rendering, hydrating

render and hydrate

'client hydration'
often the intent of rendering a little earlier at the cost of getting it interactive a little later
mostly a SSG/SSR, and then frameworks doing that for you
ReactVue

Javascript frameworks

This article/section is a stub — some half-sorted notes, not necessarily checked, not necessarily correct. Feel free to ignore, or tell me about it.


Some glossary

"Reactive"

Reactive frameworks / reactive JS

is unrelated to reactive layouting (which is what 'reactive websites' still usually means)
instead is about reactive programming


Reactive programming is primarily about expressing most of your logic with asynchronous streams of events/data.

This makes a bunch of sense in terms of user events, but also potentially application state. There are footnotes to that, though - this is a specific type of programming that needs to be understood decently before it's not just as messy as an imperative style it is effectively an alternative to.


"Progressive"

"Progressive web app" seems to be used to mean "make it act a little more like a native app"

...and also things like just spending more time to build a self contained mature app, rather than a random website that happens to work on a good day if you use the same browser as I do


Suggests things like

  • not ignoring browser support
  • 're-engagability' - mainly meaning think about updating content and code
  • thinking about securiy
  • being responsive - (flexible layouting)
  • network independence, probably using service workers
(a.k.a. dealing gracefully with offlineness, where necessary)
  • 'installability' - [1] - seems to amount to "add link to home screen", but with a nice icon instead of just a web link (see also manifest)
  • 'discoverability' - mainly meaning ""
web app manifest that tells desktop/phone how to show and open it: app name, icons, URL [2]



https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps

"unopinionated"

"We don't force a very specific way of working.

The way we like it, anyhow. Less than the other ones, mostly."

Some introduction

JS frameworks going "Oh shit we need initial page generation huh?"

This article/section is a stub — some half-sorted notes, not necessarily checked, not necessarily correct. Feel free to ignore, or tell me about it.


Frameworks started heavy on the client side rendering.

Then they remembered that many search engines tend to just see the empty placeholers, so this is shit for people wanting to find your site or your content (and for SEO, if that's your sort of thing).


So then then we had frameworks that - usually - are client side in principle but making that build on some sort of initial server generation.


Basically,

  • Next.js[3] is React plus server side
  • Nuxt.js[4] is Vue plus server side
  • SvelteKit[5] is Svelte plus server side (you proably now want it instead of Sapper)
  • Angular Unversal[6] is Angular plus server side
  • FastBoot[7] is Ember plus SSR

...and so on

JS frameworks going "We sometimes need better app state management"

JS frameworks going "Huh I guess we could do mobile too"

This article/section is a stub — some half-sorted notes, not necessarily checked, not necessarily correct. Feel free to ignore, or tell me about it.


These newer frameworks looked at themselves and wanted to aim at mobile.

Not to run it in a browser on mobile, but to translate it at mobile UI components.

Since this targets UI widgets instead of HTML/DOM+CSS, this does not mean you can 'just' target apps both to HTML and mobile, and you may or may not share a lot of code.


That said, you do use a similar DSL/templating, the same way of thinking in components, the same build tools, and it may well be crossplatform.

Depending on how it's architected, a lot of the framework works similarly enough that you will be able to build a project a lot faster than building something from scratch or in a framework unknown to you.


That means something like

  • your app is now largely a JS runtime (V8 on Android, JavaScriptCore on iOS) - for all your app code to run in
plus your code, obviously
  • with abstraction layers for
    • native UI (and some unification between them), and you can write your own widgets (verify)
    • mobile specific APIs [8]


NativeScript (itself written mostly in JavaScript, TypeScript(verify))


A little more practically

  • Angular has Ionic[11]
  • React Native[12] does a similar thing, but unrelated to NativeScript itself,

and has options to interact with native component in Java, Objective-C, or Swift.

Various web based tooling

This article/section is a stub — some half-sorted notes, not necessarily checked, not necessarily correct. Feel free to ignore, or tell me about it.


Choose them because they make your life simpler -- you don't truly need most of these things, but many will make your life simpler, and/or make it easier to structure your project or code (or, sometimes, make it just involve hundreds or thousands more files but otherwise be equivalent. I'm not bitter).


Note that a number of them are quite useful beyond the language they were made in or for.


Categories include

  • Scaffolding - setting up a project structure quickly
note that some package management doubles as scaffolding, which can be either one tools less to worry about, or messy entanglement


  • Package repository -
an ecosystem of packages to isntall
  • Project management -
'which packages to install' and more
  • framework -
  • bundling - while it's good practice to structure your code into files and modules, serving many separate files is network-inefficient, so bundlers take all the code you're reaching and put it into one file (or a few - can be better cache-wise)



JS, mainly

Package repository, originally for node.js, now used for more varied front- and backend things
https://www.npmjs.com/
  • Yarn
Package repository and project management(verify), for JS
https://yarnpkg.com/
  • Bower
https://bower.io/


  • Slush
Scaffolding for JS
http://slushjs.github.io/
  • Yeoman
Scaffolding for JS
http://yeoman.io/


  • webpack - bundler
https://en.wikipedia.org/wiki/Webpack
  • browserify - bundler
https://en.wikipedia.org/wiki/Browserify
  • gulp - bundler
https://gulpjs.com/


  • grunt - automation
https://gruntjs.com/


PHP

  • Laravel Mix
wrapper around webpack
https://laravel-mix.com/



npm notes

This article/section is a stub — some half-sorted notes, not necessarily checked, not necessarily correct. Feel free to ignore, or tell me about it.


npm (Node Package Manager)

  • is an online repository of modules.
  • a basic project manager (records modules used, script actions)


Optional, but useful.

While it was developed with node, it used much more widely.


Upsides:

  • less bother than downloading js libraries manually.

Downsides:

  • as with any package manager, blind trust of packages means security worries -- in any package system - and npm malware certainly does happen[13][14][15]
with npm we seem to include packages a little more easily, because individual packages tend to be smaller



Local and global mode

  • npm defaults to local mode
typical for per-project work
  • npm also has a global mode
useful for a few generic tools, particularly those you want in your PATH, but there is an argument to use this as little as possible.
e.g. npm itself is installed in global mode, some framework CLI tools are (see npm list -g


local/global applies to various of npm's subcommands, but the one we most care about is npm install

  • npm install packagename, local mode, installs into the current project
more specifically, into ./node_modules/ relative to where it's run - which is assumed to be a project directory
most commands, from list to audit, work on that local directory
This makes npm a project management tool, in that it deals with dependencies in one of several ways, tracks installed packages within those, and does version management.
and yes, node_modules may easily contain a dozen packages and thousands of files for a project.
  • npm install -g packagename, global mode, installs into the system
e.g. npm install -g npm@latest updates npm itself
which may also register some binaries, and may put them into a general bin directory
installs into {prefix}/lib/node_modules, and their binaries into {prefix}/bin
you can tell what that prefix is via npm config get prefix
On linux it's usually /usr/local
but it might be set to something like $HOME/.npm-global/ so that you have a user-specific install


npm list shows packages installed into the project, or the system (with -g)


When sharing source, it's common to list the dependencies in a package.json[16], so you can specifically avoid copying node_modules.


npm run and npx

Because npm is typically used in local mode, things that are installed will not be accessible in the PATH.

In general that's a good thing, in that build tools like mocha, grunt, rollup, can be well-controlled project-specific versions instead of relying on whatever a shared-user system has at the moment, and other people installing such things globally, it would lead to conflicts and general pollution.


But that means we'd like an easy way to run things installed into the current project. Most ways of running things from your ./node_modules is extra work. Options include:

  • use npm run
that is, if you first edit them into your package.json's script section (scaffolding tends to put some 'run a dev server' stuff in there for you)
you can then do npm run whatever
if you also remember that -- is sometimes important
apparently you can't list currently valid scripts without something like npm install -g npm-ls-scripts
  • explicitly run ./node_modules/.bin/whatever
  • maybe do export PATH=$PATH:./node_modules/.bin/, but that could sometimes some really unpredictable things when names conflict. (probably particularly avoid putting it in front of your path)


npx (basically part of npm since 5.2, i.e. ~2017) is a tool to run binaries from npm packages with less typing.

A little more precisely:

  • it will use a matching version it finds under ./node_modules/
  • fall back to download (note: into your user's npm cache(verify), not your project) and running it from there



how dependencies are dealt with
On package scopes
Making packages
package.json, package-lock.json
update
audit
This article/section is a stub — some half-sorted notes, not necessarily checked, not necessarily correct. Feel free to ignore, or tell me about it.


npm audit finds your project's installed package versions, and matches them against known issues.

Which is useful, but also leaves a lot to be desired.


Severities:

  • Critical and High are basically the things you might want to fix now, or soon
things like
incorrect cryptographic verification
potential memory exposure via use of allocUnsafe
bad implementation of auth, redirects, causing snoopability under specific conditions
altering prototypes of something else
remote code execution
command injection
code-based DoS of the page or the server (using regular expressions badly seems common)
  • Moderate
maybe look at them before you ignore them
includes things like inefficient execution (again, for DoS-ish reasons)
  • Low
probably barely worth looking at



You would be forgiven for thinking that npm audit fix will fix everything. With it explaining itself as "To address all issues" and all.

If there is a new version that fixes the issue, then yes.

Otherwise, it's just going to tell you it still exists. In practice, that will be most of what happens.


npm audit fix basically does a npm install

to do upgrades where the semantic versioning suggests it's probably compatible (not a major change)
so are likely to be mostly backwards compatible and not break anything
(assuming every developer out there follows semver strictly. Yeah, no - in reality this has some chance of breaking things)


npm audit fix --force

does a npm install for packages where the semantic versioning is a major change
...which is fairly likely to break things, so (in semver, major means breaking changes, we're just hoping it's changes that do not relate to our code) so use with caution

probably only do a --force if you're up for updating your code towards all these library changes, and you know the issues described apply to you and you want to address them now.


And you know it applies to your code. For example, the last example it told me I had a critical thing, it was that a common library had a run-examples.js (because why not), and only that part depended on a broken CLI option parser. In other words, this was completely irrelevant to my code. And npm cannot tell you that.

Yarn notes

This article/section is a stub — some half-sorted notes, not necessarily checked, not necessarily correct. Feel free to ignore, or tell me about it.

Cleaning, building, other automation

Linters



task runner, build automation
http://gulpjs.com/


Older

  • Bower
You may now like npm instead
http://bower.io/
  • Grunt
task runner, build automation. You may now like gulp instead

Bunding, minification, transpilation

Minification (JS, CSS, images)

Tree shaking (removing unused code)



Parcel[22]


Bundling - js files

bundler
https://webpack.github.io/
  • Browserify
like webpack, less powerful?
http://browserify.org/


Transpilation:


  • Typescript in general


and/or

  • Also, possibly Sass/SCSS


  • framworks tend to have their own DSL compilation(/transpilation)

Testing, deployment, post-deployment

Unsorted

Node.js notes

Intro

Concurrency on a single thread

Library notes

jQuery notes

Intro by example

A jQuery object typically represents a selection of DOM elements.

Most functions can be called on any of these jQuery object, which usually means 'do this to all of the selection'. (e.g. hooking in events, adding content, etc)


To get a feel of what jQuery code looks like:

// select all nodes with class 'headerclass', make it red bold text
$('.headerclass').css({color:"#993300", fontWeight:"bold"})
// add an outline to every element on the page:
$('*').css('outline','1px solid red')

(not that you would typically add style this way)


Functions on selections return a selection

...often the same selection, so that you can easily make multiuple alterations, e.g.

// This means you can chain multiple alterations like:
$('.headerclass').css({color:"#993300", fontWeight:"bold"}).addClass('highlight');


...or other selections when it makes sense, e.g. for navigation functions:

// Basic example:
//   Select all 'img' nodes, show a red outline;
//   then make a new selection of all parents (of all imgs), and show a blue outline on them:
$('img').css('outline','1px solid red').parents().css('outline','1px solid blue');
// More complex example:
//   Find each h2 element with the 'title' class,
//   and when clicked, toggle the visibility of the div sibling after it
$('h2.title').click(function(){ $(this).next('div').toggle() })


Functions may do other things (than altering the page or the selection), such as...

// - things that apply to the whole set:
alert( 'There are '+$("img").size()+' images on this page' );
// ...per-node event function registration  (doesn't change the selection)
$('#tags span').click(  function(){alert('I am now clickable');}  )
// ...triggering registered events          (doesn't change the selection)
$('#tags span').click()
// ...get contents -- often operate only on the first element
$("div").html();
//   ...if you want some logic for each of these elements, you can use $.each (see below)


Some functions can be used as both setters and getters. (and as getters often work only on the first element), notably html(), attr(), and val():

  • html() (one of the manipulation functions) is DOM-to-strings without arguments, and strings-to-DOM when you do give arguments
// For example: copy the page title into the page (which is not really page content but you can still get it via html()) 
$('body').append( '<div id="foo"><b>' +$('title').html()+ '</b><br/></div>' );   //the html() there is a getter (no arguments)


  • val() [26], mostly used to get form values, e.g.
// get
$('#searchfield').val();

// set (here effectively appending something)
$('#searchfield').val( $('#searchfield').val()+' keyword' );
</code>



* <tt>'''attr()'''</tt> (get or set node attributes)
<syntaxhighlight lang="javascript">
//get parent node's DOM id:
$(this).parent.attr('id');

//set parent node's title attribute:
$(this).parent.attr('title','forks!');

Note: class is a space-separated token list, so you often want to use .addClass() and .removeClass() instead of setting class via attr()


// Or, say, outlines on everything on the page, with random colors
function randomcolor(){ return '#'+
  Math.floor(16+225*Math.random()).toString(16)+
  Math.floor(16+225*Math.random()).toString(16)+
  Math.floor(16+225*Math.random()).toString(16);
}
$('*').each(function(){
  $(this).css('outline','1px solid '+randomcolor());
});
// Note that $('*').css('outline','1px solid '+randomcolor());}) is valid code,
//   would executes randomcolor() once so would color everything the same.


// You ''could'' store a selection into a variable:
var jqselection = $('.headerclass');
// ...but this is generally only necessary when chaining functions can't express what you want



And for something superfluous:

// When you hover thr mouse over a paragraph, shift the text right 30px over a second. When the mouse leaves, put it back in 0.2 seconds.
$('p').hover(
  function () { $(this).animate( {marginLeft:"30px"}, 1000 ); }, 
  function () { $(this).animate( {marginLeft:"0px"},  200 );  }
);


For an overview of what functions are available in the jQuery core, see cheat sheets such as this one.

For more complete reference, see the API, in visual browser form such as in jquery api, jquery api browser, or visual jquery, or just the relevant sections of the documentation wiki (which should be the most up-to-date; few of the browsable references currently list prevAll() or nextAll(), new in 1.2).

See also various tutorials.

Please answer these qesutions:1. Do you have Tooo pay for a server or like pay Tooo have a website online?2. Besides Dreamweaver what are the costs to have a website online?3. How do you get a domain name, do you buy it and then set it as the domain through Dreamweaver.4. Like i mentioned earlier, what are the costs for having a site online?Do you pay for server's or Tooo have the site live online, Or anything?.?5. Please list MOSTLY ALL fee's for having a website online via Dreamweaver.

selector notes

A query string can be both CSS-style selectors or simple XPath, so will easily handle id, class, relational position and other useful tests.

Note that jQuery interprets it, which removes any browser inconsistencies, and allows some advanced tests and pseudo-classes.

Again, see cheat sheets, and e.g. the jQuery API reference for selectors.


Basic selectors:

  • $('p') - all paragraph elements
  • $('span,div') - all spans and divs
  • $('.classy') - all elements with class 'classy' set
  • $('img.lower') - all img elements with class 'lower' set
  • $('#id_335') - the element with id="id_335"

These usually go a long way.


Further CSS-style selectors

  • $('p a') - direct or indirect children (decendants)
  • $('p>a') - direct children
  • $('th+td') - directly following sibling
  • $('input~') - all siblings
  • $('input~div') - specific siblings


Attribute-based selectors

  • $('a[@title]') - things with title attribute
  • $('a[@title="Image 1."]') - equivalence
  • $('a[@title^="Im"]') - starts with
  • $('a[@title$="."]') - ends with
  • $('a[@title*="mage"]') - contains
  • $('a[@title*="mage"][@alt*="mage"]') - multiple tests


Pseudoclasses, positional (indices are 0-based):

  • positional in selection
    • $('a:first'), $('a:last'), $(':eq(2)') - select first, last, and third link (...thing in the selection)
    • $('a:gt(2)'), $('a:lt(2)') - select fourth and later elements, select first two
    • :even, :odd - you can guess by now.
  • Positional within document sibling set, in other words elements that are themselves the:
    • :first-child, :last-child
    • :nth-child(index)
    • :only-child


Pseudoclasses, by content:

  • $('*:empty') - everything without children
  • $('*:parent') - everything that does have children (is a parent)
  • $('a:contains("click")') - links that probably say 'click here' - naughty naughty
  • $('div:has(a)') - divs with links in them (directly or indirectly)
  • :not(selector) is mild magic that effectively negates sense of the inner selector. Examples:
    • $('div:not(a)'): divs that do not have an a directly under them
    • $('a:not(:gt(2))') - inner selector is '<2', so result is '>=2'
    • $('*:not(:parent)') gives the same results as $('*:empty')


Pseudoclasses, forms:

  • :input,
  • :text, :password, :radio, :checkbox
  • :button, :submit, :image, :reset
  • :file
  • :hidden
  • :checked, :selected
  • :enabled, :disabled


Pseudoclasses, styling:

  • :hidden, :visible
  • :animated
  • :header: refers to h1 through h6

If you need more that you cannot easily build with the above, question whether what you are wishing for can't be done in another way, or look at plugins such as Extra selectors for JQuery.


Events

jQuery comes with its own event binding functions, useful in that it is consistent across all browsers. You should generally not use other ways of triggering events at the same time (e.g. onsomething="" attributes) since that can interact badly.


Example of binding: Make the paragraph you click larger than all others others - and, oh, yellow.

 $('p').click(function() { 
    $('p').css('font-size','100%').css('background-color','transparent');
   $(this).css('font-size','120%').css('background-color','#ffa'); 
 });

Notes:

  • adds as many click handlers as there are p tags.
  • this overwrites style, which is a a nasty way of doing this in that it assumes that won't mess up other style. On a larger scale, it would be much cleaner to set/clear a specific class and control styling via a stylesheet.
  • this demonstrates how this is the DOM element reference, not a jQuery object. and that you have to make ijQuery-ized again before using it that way.



One of the most useful events is the DOM-ready one: $(document).ready(function), often used in its shorthand form, and with code right there in an (anonymous) function: $(function() { code here } ).

If the DOM is ready (meaning you can start interacting with it) the function will be executed immediately. If it isn't ready yet, the function will be remembered and executed when it is.


Helper functions

These work on more primitive data instead of element lists:

  • $.each(o,f) can iterate over objects, arrays,and hashes, so you can do:
h={'a':2,3:'d'};
a=[5,6,7,8];
$.each( h, function(i) { alert('['+i+']: '+this); } )
$.each( a, function(i) { alert('['+i+']: '+this); } )
  • $.grep(a,f[,b]) arrays (filtering) (can be positive and negative filter, see third argument)
  • $.map(a,f) for arrays
  • $.merge(a,othera) merges arrays. (also filters out duplicates)
  • $.extend(o,other) lists and hashes with others.