Javascript Flashcards
D3: A good way to visualize binned data is
as shapes.
D3: The three most popular D3 libraries are
dimple.js, Rickshaw, NVD3
D3: The best D3 library for time series or streaming data is
Rickshaw
D3: The DOM gets created during
page load
Javascript: To clear the javascript console, type
clear()
Javascript: In the javascript console, to return the html of the current page that has a certain css id, type
document.getElementById(“cssid”)
Javascript: In the javascript console, to return the html of the current page that has a any css selector, type
document.querySelector(“.css-class”)
D3: To select elements using D3, type
d3.select(“.css-class”)
D3: To select a DOM element and then change its css styled color, type
d3.select(“.css-class”).style(“background-color”, “green”)
D3: To check if the element you are selecting is unique, you can type
d3.selectAll(“.css-class”)
and then make sure the array returned has one item.
D3: To select a DOM element and then change its text, type
d3.select(“.css-class”).text(“New Text”)
D3: To select an element within your current selection, type
current_selection_var.select(“.inner-class”)
D3: To change an html attribute, type
d3.select(“.css-class”).attr(“attribute_name”, “new value”)
javascript: To set a string to uppercase, type
string_var.toUpperCase()
javascript: To create a function, type
function fuctionName() { }
javascript: To create an anonymous function, type
var functionVar = function () { };
note: requires semicolon
javascript: To create a function that returns a string, type
function fuctionName() { return "string" }
jQuery: To hide an html element with the class=”class”, type
jQuery(“.class”).hide();
jQuery: To show an html element with the class=”class” slowly, type
jQuery(“.class”).show(“slow”);
jQuery: The abbreviation for jQuery is
$
jQuery: Most jQuery methods return
the item selected, which allows for method chaining.
javascript: To return all of the html tags of the body of a page, type
document.body.children
javascript: To return all of the html tags on a page with a certain class name, type
document.getElementByClassName(“class”)
jQuery: In the jQuery docs, animations are categorized as
Effects
jQuery: To run a function when the DOM loads, type
$(document).ready(myFunction)
or
$(myFunction)
jQuery: When manipulating the DOM using javascript it is a best practice to
not create a script that runs on ready and just add your script at the bottom of the body and assume it is ready.
jQuery: To add html to an html element based on it’s class, type
$(“.class”).append(“-button>String-/button>”)
jQuery: To remove the code for the precise button you are clicking, type
$(“button”).click(function() {
$(this).remove();
});
jQuery: To traverse to the previous sibling page element before the element you selected by class, type
$(“.class”).prev()
jQuery: To prevent a link from taking you to the next page, type
$(“a”).click(function(event) {
event.preventDefault();
})
jQuery: To return the href of the link you just clicked, type
$("a").click(function() { var my_attribute = $(this).attr("href"); })
jQuery: To turn a string into a jQuery representation of a page element, type
var $my_element = $(-div>-/div>)
jQuery: To signify that a variable is a jQuery object, people ofter
add a $ to the beginning of the variable name
jQuery: The append method appends to
the end but still inside the tags you point at.
jQuery: To use attr() to add an attribute to an element, type
$(“.class”)attr(“key”, “value”);
jQuery: To append text into a tag, type
$(“.class”).text(“string”)
ajax was originally called
xml http requestobject
ajax: To make a web page know that it will work with ajax, add to the head
-script>
var xhr_object = new XMLHttpRequest();
-/script>
ajax: a good response has the readyState value of
4
ajax: the servers response is held in an attribute called
xhr_object.responseText
ajax: To create a button that triggers the send method of an xhr_object, type
function sendAjax () { xhr_object.send() }
-button onClick=”sendAjax()”>String-/button>
ajax: The steps to use ajax are
create an xhr_object
set a response function
open the request
send the request
ajax can only send requests to
one server
ajax: To overcome ajax’s one host policy you can
have your server call the additional servers.
ajax: To get images, css files and javascript files from an additional server, you can use
jsonp
javascript: To go to a different url, type
window.location.replace(“http://www.google.com”);
javascript: To return the url (including query string) of the current page, type
window.location.href
javascript: to slice a string, type
string_var.slice(1,5);
javascript: To return the index of a string, type
string_var.indexOf(“substring”);
javascript: To make a div immediately scroll itself to the bottom, type
document.getElementById(‘div-id’).scrollTop = document.getElementById(‘div-id’).scrollHeight;
javascript: To return the query string (including the “?”), type
window.location.search
AJAX: long polling is
When the client sends a request to the server and the server makes the client wait until an event occurs before sending the data back, and then the client makes another long request.
jQuery: To run a function upon every mouse movement, type
$(window).mousemove(function(event) {
console.log(event.type)
});
jQuery: To run a function when the mouse leaves the window, type
$(document).mouseleave(function(){
console.log(‘string’)
})
jQuery: To set or update a css property for a class, type
$(“.css-class”).css( “property”, “value”)
jQuery: To effectively remove a css property, type
$(“.css-class”).css(“property”, “”)
javascript: To set a cookie on the browser, type
document.cookie=”key=a value; expires=Thu, 01 Jan 2016 12:00:00 UTC; path=/”;
javascript: To delete a cookie
update it with an expiration date that is in the past.
javascript: To return the cookies on the browser, type
document.cookie;
javascript: To save the return of a confirm box into a var, type
var confirm_var = confirm(“Accept or Cancel?”);
javascript: The return of a confirm box is
accept: true
cancel: false
ajax: each different type of ajax request you plan to make should
have its own xhr_object
ajax: The xhr_object attribute that contains the state of the request, e.g. 4 if the response has arrived, is
xhr_object.readystate
javascript: To change the html that is within an element, type
document.getElementById(“id”).innerHTML = “new html”
ajax: All the code necessary to send and receive an ajax request is
var xhr_object = new XMLHttpRequest(); xhr_object.onreadystatechange = function() { if (xhr_object.readystate === 4) { document.getElementById("id").innerHTML = xhr_object.reponseText; }};
xhr_object.open(“GET”, “/endpoint?key=value”)
xhr_object.send();
jQuery: To send an ajax request and then inject it into a page element using jquery, type
function functionName() { $(".css-class").load("/endpoint?key=value"); };
javascript: At the end of if statements. do not put
semicolon
javascript: User inputs that are numbers must be converted from
string to integer.
javascript: The “equal to” operator for javascript conditional statements is
===
javascript: To create a conditional statement, type
if (4 === 4) {
document.write(“Equal”);
}
javascript: To create an if else clause, type
if (my_int === 4) { document.write("Equal"); } else { document.write("Not Equal"); }
javascript: strict equality operators (===) do not
convert a string to a number.
== does
javascript: The scrict not equals operator is
!==
javascript: Boolean values in javascript are
written in lower case. eg. false, true
javascript: An “else if” statement is written as
if () {
} else if () {
}
javascript: To use two conditional statements, use
double ampersand
javascript: To create a single line comment in a javascript file, type
//
bower is a
front end package manager that allows you to easily download from one place.
node: To print an error to the console, type
console.error(errorMessage);
node: A callback function is
the function that executes when a response to a request is received.
Javascript: To erase whatever is in the browser console, type
clear()
Javascript: To return a rounded number from a float, type
Math.round(2.2)
ajax: To send an ajax request for the next page of django’s pagination every time a user scrolls to the bottom, type
var is_active = false var page_num = 1 $(window).scroll(function() { if(!is_active && $(window).scrollTop() + $(window).height() + 100 > $(document).height()) { $.get('http://endpoint.com?page=' + page_num, function(data){ $(".gallery").append(data) is_active = false page_num += 1 }); } });
jQuery: jQuery selectors select matching elements that
exist in the DOM when the code is executed, and don’t dynamically update.
jQuery: in order to keep dom objects selected even after the initial jQuery execution, (e.g. when loading new objects from ajax), you can use
$(document).on(“click”, “.css-class”, function() {
});
maps: To render a map
import maps api before body end
-script src=”https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap” async defer>
create container div
<div></div>
var map; function initMap() { var map = new google.maps.Map(document.getElementById('map'), mapOptions); }
Note: must add mapOptions json to the initMap function before the map var
maps: To get the coordinates of a device, type
navigator.geolocation.getCurrentPosition(success);
maps: the success callback function of navigator.geolocation.getCurrentPosition(success); should start with
function success(pos) { var crd = pos.coords; var lat = crd.latitude; var lng = crd.longitude; }
javascript: To write code that will only execute after a set amount of time, type
setTimeout(function(){
console.log(“string”)
}, 2000);
note: this is 2 seconds
ajax: To create an ajax request using $.get, type
$.get(‘http://endpoint.com?key=value’, function(data){
console.log(data);
});
javascript: To turn an int into a string, type
var num = 15; var n = num.toString();
javascript: To simulate a button click, type
document.getElementsByTagName(‘button’)[0].click();
javascript: When you use window.location.replace(“http://url.com”)
it does not let the user return to the original page
maps: To disallow dragging, type
var mapOptions = { draggable: false, }
maps: to create a marker, type
var marker = new google.maps.Marker({ position: {lat: 11.111, lng: 22.222}, map: map, title: 'String' });
jquery: To create a function that executes immediately, type
$(function() {
});
javascript: To reload a window, type
location.reload();
maps: To get all the data to the browser you should
send it all in json and then unpack it with javascript, rather than try to server side render
maps: To make a marker with a new icon image, type
var marker = new google.maps.Marker({ position: myLatLng, map: map, icon: 'http://cdn.com/file.png' });
ajax: get generic ajax loading gifs with a transparent background at
www.ajaxload.info/
ajax: To make an ajax loading symbol come up
add a gif image to the bottom of the page display:none; and when you send the ajax request, set it to initial, and then back to none in the callback function
javascript: To make a python style for loop in js, type
myArray.forEach(function(value, index) {
console.log(value);
})
node: To import a library, type
var libraryName = require(“libraryName”)
node: To turn a json string into a json object, type
JSON.parse(jsonString)
node: To turn a json object into a json string, type
JSON.stringify(jsonObject)
node: you can access value one in var jsonObject = {key1: “value1”} by typing
jsonObject.key1
node: To import a file in the same directory, type
var myFile = require(“./myFile”)
nore: the ./ path is mandatory
node: To expose a function to people importing your file, type
module.exports.exposedFunctionName = localFunctionName;
node: To access any arguments you pass into the command line when running a script e.g. node script.js param1 param2, type
process.argv.slice(2)
node: To go to a local host port, type the url
http://localhost:1337/
node: To create a server, type
var http = require(‘http’);
var server = http.createServer(function (req, res) {
res.writeHead(200);
res.end(‘Hello, World!\n’);
});
server.listen(1337);
node: After the function res.end() is executes inside the response
the browser stops listening for a response
The local IP address for all computers is
127.0.0.1
node: http.createServer(myFunction(req, res)); sends your function
an argument which is a request object with has and attribute called req.url, which returns everything after the root domain including get params
javascript: To create an object using a constructor function, type
function ConstructorFunc(param1, param2) { this.attribute1 = param1; this.attribute2 = param2; this.functionName = function() { console.log("string") } }
javascript: To instantiate an object made by a constructor function, type
var myInstance = new ConstructorFunc(“param1”, “param2”)
javascript: To turn a function call into a constructor function you must
precede the function name with "new" e.g. var myInstance = new ConstructorFunc("param1", "param2")
javascript: By convention for constructor functions, people
capitalize the first letter
javascript: To add a function to a constructor function that does not reload every time the constructor function is instantiated, use
ConstructorFuncName.prototype.functionName = function() {
return “string”
}
javascript: The DOM is
the javascript representation of the page
javascript: For websites that are rendering over 75KB of JSON data, time to first paint
is lower using server side rendering on both mobile and web
javascript: For websites that are rendering below 75KB of JSON data, time to first paint is
about the same using client or server side rendering on both mobile and web
javascript: For websites that are rendering over 75KB of JSON data, time to last paint fastest on
server side rendering on both mobile and web
jquery: To return in inner html of a jquery object, type
$(“.css-class”).html()
javascript: To evaluate the key name in a json object, type
{ [varName]: “value” }
jquery: To scroll to bottom of div, type
var myDiv = $('.css-class'); var height = myDiv[0].scrollHeight; myDiv.scrollTop(height);
node: To update node, type
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
javascript: To run an anonymous function
surround it with parentheses
javascript: To create a script tag, add a src and type attribute to it and append it to the head, type
var elementName = document.createElement(“script”);
mf. type = “text/javascript”;
mf. async = true;
mf. src = “//www.cdn.com/id.js”;
document. getElementsByTagName(“head”)[0].appendChild(elementName);
javascript: To set the html of the body tag to a string, type
document.getElementsByTagName(“body”)[0].innerHTML = “script”
javascript: How jsonp works is
dynamically create a script tag with javascript
make the src the api endpoint you want
set the query string to ?callback=callbackFunctionName
this request will return your json data as an argument to a function named callbackFunctionName and will run the function so define the callback function that will handle the data before you make the dynamic script request
to return the data from api
javascipt: Jsonp is
a way to overcome the single origin policy which prevents browsers from making an ajax request to a URL other than the current
javascript: To run new javascript that was added to the page, type
eval(scriptName)
javascript: To check if a browser has a touch screen or not, type
function isMobile() { try{ document.createEvent("TouchEvent"); return true; } catch(e){ return false; } }
jquery: To run a script only if the width of the screen is something, type
$(document).ready(function() { var isMobile = window.matchMedia("only screen and (max-width: 760px)");
if (isMobile.matches) {
…
}
});
javascript: To insert a new element into the top of a div full of elements, type
parentElement.insertBefore(newElement, parentElement.childNodes[0])
javascript: To add a class to an element in vanilla js, type
document.querySelector(“div”).className += “ other-class”;
jquery: To traverse up to the parent div then to the next div, then it’s children, type
$(element).parent().next().children()
javascript: To start an html5 video at a certain spot after it loads, type
document.querySelector(‘video’).addEventListener(‘loadedmetadata’, function() {
this.currentTime = 10;
}, false);