Javascript/jQuery tips
https://stackoverflow.com/questions/6262071/what-is-the-difference-between-and-jquery
https://www.quora.com/What-is-a-difference-between-jQuery-and-JavaScript
https://medium.com/javascript-in-plain-english/yes-its-npx-not-npm-the-difference-explained-58cbb202ec33
https://medium.com/@housecor/browserify-vs-webpack-b3d7ca08a0a9
Vanilla JS
document.getElementById() //eg. 'uniqueID' document.getElementsByTagName() //eg. 'div' document.getElementByClassName() //eg. 'className' - ruturns an array (always) document.querySelector() //eg. '.className' - only selects first occurrence of CSS selector document.querySelectorAll() //eg. '.className' - returns an array
export function slugify(str) { return str .toString() .toLowerCase() .replace( /\s+/g, '-' ) // Replace spaces with - .replace( /[^\w\-]+/g, '' ) // Remove all non-word chars .replace( /\-\-+/g, '-' ) // Replace multiple - with single - .replace( /^-+/, '' ) // Trim - from start of text .replace( /-+$/, '' ); // Trim - from end of text }
How to import in modern JS
\\old syntax const express = require( 'express' ); //ES6 syntax import express from 'express';
TO DO THINGS LIKE THIS YOU NEED TO HAVE “type”: “module”
IN YOUR PACKAGE.JSON
creating event listeners
jQuery
//jquery $( 'a' ).on( 'click', function( e ) { //do something console.log( 'Event: ', e ); });
Vanilla JS
Note: Vanlla JS willnot
work in IE 8 or lower!!!
//vanilla JS - this will not work on IE8 and lower var clickHandler = function() { // Your click handler }; var anchors = document.getElementsByTagName("a"); for (var i = 0; i < anchors.length; i++) { var current = anchors[i]; current.addEventListener('click', clickHandler, false); }
- add event listeners for A tags like so
document.querySelector('#Email').addEventListener('change',function(){ document.querySelector('#UserName').value = this.value; });
- this is how you would add an on change event in vanilla JS, this also does not work in IE 8 and lower
document.getElementById("select").onchange = function() { console.log("Changed!"); }
- this does not
work: In Chrome (possibly other browsers too) the 'onchange' event is only fired when field loses focus. Not when typing in input field. Could possibly work for checkboxes maybe.
React
<input type="text" placeholder="store name" required defaultValue={ getFunName() } /> <button onClick={ this.handleClick } type="submit" className="btn">visit store </button>
- this is how you add events in JSX/React
Be careful notice difference between{ this.handleClick }
and{ getFunName() }
, the latter runs immediately when the element is added to the page
Log object to console:
console.log(JSON.stringify( object, null, 4 )) console.table(object) Object.entries(object)
LOOPS:
- for in is used for objects
- and for of loop to iterate over an array
- .map - takes a function and runs it on each item in the array
list all event listeners
btn = $('.btn'); listeners = getEventListeners(btn);
- list event listeners
debounce function
https://davidwalsh.name/javascript-debounce-function
// Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; var removeOverlayOnResize = debounce(function() { $('.body-wrapper .overlay').toggleClass('d-none'); }, 500); $(window).on( 'resize', removeOverlayOnResize );
- JavaScript Debounce Function
stopPropagation vs preventDefault
stopPropagation stops the event from bubbling up the event chain.
preventDefault prevents the default action the browser makes on that event.
Difference between jQuery parent(), parents() and closest() functions
closest() selects the first element that matches the selector, up from the DOM tree.
parent() selects one element up the DOM tree.
parents() method is similar to parent() but selects all the matching elements up the DOM tree.
https://stackoverflow.com/questions/2802055/what-does-the-construct-x-x-y-mean
Function/Replacement for id or class
var id = "!@#$%^&*()_+1234567890-=abcdefghijklmnopqrstuvwxyzHere is a really long sting full of shit's & giggles"; id = id.replace(/[^a-z0-9\-_:\.]|^[^a-z]+/gi, "");
- output _1234567890-abcdefghijklmnopqrstuvwxyzHereisareallylongstingfullofshitsgiggles
express try catch example:
app.get('/search', function (req, res) { // Simulating async operation setImmediate(function () { var jsonStr = req.query.params try { var jsonObj = JSON.parse(jsonStr) res.send('Success') } catch (e) { res.status(400).send('Invalid JSON string') } }) })
express example of promise
app.get('/', function (req, res, next) { // do some sync stuff queryDb() .then(function (data) { // handle data return makeCsv(data) }) .then(function (csv) { // handle csv }) .catch(next) }) app.use(function (err, req, res, next) { // handle error })