Countdown animation

26. July 2022

HTML:

<span class="countdown">500</span>

jQuery:

var $count = $('.countdown');

var num = parseInt($count.text());
var interval = window.setInterval(updateTime, 1000);

function updateTime() {
  num--;
  $count.text(num.toString());
  if (num <= 0) {
    window.clearInterval(interval);
  }
}
Check if mobile with React useEffect

22. June 2022

const [width, setWidth] = useState<number>(window.innerWidth);

function handleWindowSizeChange() {
    setWidth(window.innerWidth);
}
useEffect(() => {
    window.addEventListener('resize', handleWindowSizeChange);
    return () => {
        window.removeEventListener('resize', handleWindowSizeChange);
    }
}, []);

const isMobile = width <= 768;
Add class to body with React

20. June 2022

const [isOpen, setIsOpen] = useState(false)
useEffect(() => {
  document.body.classList.toggle('class-open', isOpen);
},[isOpen])
    
<button onCLick={()=> setIsOpen(!isOpen)}>Toggle Class</button>
Do things with radio button

15. April 2021

jQuery('input:radio[name=customer_type]').change(function() {
			
if (jQuery(this).is(':checked') && jQuery(this).val() == 'company') {
    jQuery('form.woocommerce-checkout').css('display', 'block');
    jQuery('.info-message-for-private').css('display', 'none');
  }
			
if (jQuery(this).is(':checked') && jQuery(this).val() == 'private') {
    jQuery('form.woocommerce-checkout').css('display', 'none');
    jQuery('.info-message-for-private').css('display', 'block');
  }	
});
Check checkbox

17. September 2020

var checkbox = document.querySelector("input[name=checkbox]");

checkbox.addEventListener( 'change', function() {
    if(this.checked) {
        // Checkbox is checked..
    } else {
        // Checkbox is not checked..
    }
});

jQuery:

$('input[name=checkbox]').change(function(){
    if($(this).is(':checked')) {
        // Checkbox is checked..
    } else {
        // Checkbox is not checked..
    }
});
Sort a list of divs regarding of they have a specific Class

10. October 2019

// This function rearrange the 'list' of divs.
function arrangeList() {
	// New array of divs
	var newArray = [];
	// Get all the elements that are going to be sorted
	var dis = document.getElementsByClassName('selectRoom');
	// New array for all the elements that should be in the bottom
	var disabled = [];
	for(var i = 0; i < dis.length; i++) {
		if (!dis[i].classList.contains('roomDisabled')) {
			newArray.push(dis[i]);
		} else {
			disabled.push(dis[i]);
		}
	}
	// Make a new array for the newest list of element
	var newestArray = newArray.concat(disabled);
	// Find the parent do put the new list into
	var parent = document.querySelector('.table-sorting');
	parent.innerHTML = '';
	// ecma 5
	newestArray.forEach(function (element) {
		parent.append(element);
	});
}

Hover another element

27. May 2019

var filter = 'invert(60%) sepia(35%) saturate(448%) hue-rotate(282deg) brightness(97%) contrast(90%)';

jQuery(".hover-example a").hover(function(){
    jQuery("img").css("filter", filter);
    }, function(){
    jQuery("img").css("filter", "none");
});
Check what browser

22. May 2019

function myFunction() { 
     if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ) 
    {
        alert('Opera');
    }
    else if(navigator.userAgent.indexOf("Chrome") != -1 )
    {
        alert('Chrome');
    }
    else if(navigator.userAgent.indexOf("Safari") != -1)
    {
        alert('Safari');
    }
    else if(navigator.userAgent.indexOf("Firefox") != -1 ) 
    {
         alert('Firefox');
    }
    else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
    {
      alert('IE'); 
    }  
    else 
    {
       alert('unknown');
    }
}
Angular 2 nice to know

19. March 2019

ng new myProject --style=scss //create a new project (u need to have 'npm install -g @angular/cli' for the command to work)

ng generate component myComponent //create a new component inside the project

ng generate service myService //create a new service

Remember anything with the .spec after we don’t edit.

Vue, nice to know!

4. March 2019

https://v1.vuejs.org/guide/syntax.html
https://v1.vuejs.org/guide/computed.html
https://v1.vuejs.org/guide/class-and-style.html
https://v1.vuejs.org/guide/conditional.html
https://v1.vuejs.org/guide/list.html
https://v1.vuejs.org/guide/events.html
https://v1.vuejs.org/guide/forms.html

Ex: v-bind:value="email" -> shorthand -> :value="email"
v-model:value="email" -> lets the browser update the value
v-on:click.prevent="process" -> a click event. Will have to define a method called process. .prevent stops the function to refresh the site if its a button.
Shorthand for v-on:click is @click

To access Vue component from console, define it as a variable:
	var vm = new Vue({
		el: '#app',
		data: {
			message: 'Login details',
			username: '',
			email: thomaskarlandersson@outlook.com,
		},
		methods: {
			process: function() {
		            console.log('the button was clicked' + this.email);
		        }
		},
	});

jQuery nice to know

25. February 2019

$(‘.myClass’) - Targets myClass
$(‘img.myClass’) - Targets tag img that has myClass class
$(‘p’) - All P in the DOM
$(‘*’) - All the elements in the DOM
$(‘h1:first’) - First H1 in the DOM
$(‘.myClass h1:first’) - First H1 in the myClass container
$(‘.myClass h1:even’) - Selects all even H1 in the myClass container
$(‘:checked’) - All elements that are checked
$(‘.myClass p:not(p:eq(2))’) - Selects all P in myClass except the P that have the index of 2 (remember, it is zero index)
$(‘div > p’) - Select all P that are direct child of DIV
$(‘ul + div’) - Select the DIV that are next to a UL
$(‘p[class]’) - Select all the P that have a class attribute
$(‘p[id^=pro][lang*=en-]’) - Select all the P that have a ID attribute that starts with PRO and a Lang attribute that contains en-
$(‘p:contains('3')’) - Select all the P that contains the text string 3. 
$(‘p:parent’) - Select all the P that contains something
$(‘div p:nth-child(2)’) - Select all the second P that are inside of a P inside of the div. 
$(‘div p:nth-child(3n)’) - Select every 3third P that are inside of a P that are inside of a div.

$(‘#example’).find('.myClass'); - Search the #example to find .myClass.
$(‘p’).css(‘color’,’blue’); - All P color:blue;
$(‘p:not(.myClass)’).css(‘color’,’blue’); - All P that not have the class myClass with color:blue;
$(‘.myClass’).pretend('YO'); - Targets myClass and inserts YO in the beginning of myClass
$(‘.myClass’).html('<h1>Yo</h1>'); - Insert HTML element
$(‘.myClass’).text('<h1>Yo</h1>'); - Insert as plain text
$(‘.myClass’).load('example.html'); - Inserts example.html into myClass

$( "li[class^='myCla']" ).css("display", "none"); - Find LI where the class name starts with 'myCla' and apply css.

Simple animation example:
$(document).ready(function() {
  $("h1").click(function() {
    $("h2").animate({
      font-size: "toggle", //Can be Hide or Show or Toggle
      width: "30%",
      top: "+=100px"
    }, 1000, 'swing', function() {
      $("h3").fadeOut(2000); //This happens after the first animation
    });
  });
});
Function to disable right click on WooCommerce product gallery

25. February 2019

/**
 * Disable right-mouse-click on images in WooCommerce product gallery
 */

setTimeout(function(){

  var zoomImage = document.querySelector('.zoomImg');
  zoomImage.setAttribute('oncontextmenu', 'return false');

  var flexActive = document.querySelector('.flex-active');
  flexActive.setAttribute('oncontextmenu', 'return false');

  var trigger = document.querySelector('.woocommerce-product-gallery__trigger');

  trigger.addEventListener('click', function () {
    setTimeout(function () {
      var pswpImg = document.querySelector('img.pswp__img');
      pswpImg.setAttribute('oncontextmenu', 'return false');
    }, 100);
  });
  }, 2000);
Nice JS function :-)

17. February 2019

const body = document.querySelector('body');
const linksOnFrontpage = document.querySelectorAll('.box-with-border-bottom');

    for (const link of linksOnFrontpage) {
    	link.addEventListener('click', () => {
    		console.log(link.id);
    		const clickLink = document.createElement('a');
    		clickLink.id = 'javascriptClick-' + link.id;
    		clickLink.href = 'https://example.com/products/#' + link.id;
    		body.appendChild(clickLink);
    		document.getElementById('javascriptClick-' + link.id).click();
    	})
    }
Function to create a movement of some item while scrolling

29. January 2019

// Defining the menu items
let topItemOne = document.querySelector('#menu-item-239');
let topItemTwo = document.querySelector('#menu-item-240');
let topItemThree = document.querySelector('#menu-item-241');
let topItemFour = document.querySelector('#menu-item-242');

// Defining where the breakpoint is
let breakPointOne = document.querySelector('#breakpoint1');
let breakPointTwo = document.querySelector('#breakpoint2');
let breakPointThree = document.querySelector('#breakpoint3');
let breakPointFour = document.querySelector('#breakpoint4');

window.addEventListener('scroll', function(ev) {

	let distanceToTopOne = breakPointOne.getBoundingClientRect().top - 110;
	let distanceToTopTwo = breakPointTwo.getBoundingClientRect().top - 110;
	let distanceToTopThree = breakPointThree.getBoundingClientRect().top - 110;
	let distanceToTopFour = breakPointFour.getBoundingClientRect().top - 110;

	if (distanceToTopOne > 0) {
		topItemOne.classList.remove('focccus');
	}

	if (distanceToTopOne < 0) {
		topItemOne.classList.add('focccus');
	}

	if (distanceToTopTwo > 0) {
		topItemTwo.classList.remove('focccus');
	}

	if (distanceToTopTwo < 0){
		topItemTwo.classList.add('focccus');
		topItemOne.classList.remove('focccus');
	}

	if (distanceToTopThree > 0) {
		topItemThree.classList.remove('focccus');
	}

	if (distanceToTopThree < 0){
		topItemThree.classList.add('focccus');
		topItemTwo.classList.remove('focccus');
	}

	if (distanceToTopFour > 0) {
		topItemFour.classList.remove('focccus');
	}

	if (distanceToTopFour < 0){
		topItemFour.classList.add('focccus');
		topItemThree.classList.remove('focccus');
	}
});
For of loop to loop querySelectorAll

29. January 2019

const body = document.querySelector('body');
const linksOnFrontpage = document.querySelectorAll('.box-with-border-bottom');

for (const link of linksOnFrontpage) {
   link.addEventListener('click', () => {
      console.log(link.id);
      const clickLink = document.createElement('a');
      clickLink.id = 'click-' + link.id;
      clickLink.href = 'https://website.com/products/#' + link.id;
      body.appendChild(clickLink);
      document.getElementById('click-' + link.id).click();
   })
}
Async / Await

23. November 2018

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();

Source

Add a text before some DOM element content

14. November 2018

var body = document.querySelector('body');

if (document.body.classList.contains('woocommerce-checkout')) {
    var wooBillingField = document.querySelector('.woocommerce-billing-fields');
    var additionalText = document.createElement('p');
    additionalText.innerText = 'Some text';
    wooBillingField.insertBefore(additionalText, wooBillingField.firstChild);
}

 

How to target the parent element

2. November 2018

HTML:

<div class="myParent">
	<div class="myChildren"></div>
	<div class="myChildren"><span class="break">09:00</span></div>
	<div class="myChildren"></div>
	<div class="myChildren"></div>
</div>

CSS:

.extraCssToParent {
    background: peru;
}

jQuery:

jQuery(function($) {
    $(".myParent .break").parents(".myChildren").addClass( "extraCssToParent" );
});

 

React create-react-app – nice to know

13. October 2018

If you dont have create-react-app installed, run: npm install -g create-react-app (you only have to do this once on your mac)

To start a new project, cd into your folder and Run: create-react-app name-of-the-app

When that is finished, cd into your name-of-the-app folder and run: npm start

To install react icons: npm install save react icons

To make a ‘build’ out of your react app, stop the npm start command (option + c) and then run: npm run build now you have a new folder in you project, called build.

Making AJAX calls

2. October 2018

// create a function that will take specified URL and return data to us
function makeAjaxRequest(URL, callbackFunction) {
	var httpRequest = new XMLHttpRequest();
	httpRequest.onreadystatechange = function () {
		if (httpRequest.readyState === 4) {
			if (httpRequest.status === 200) {
				var data = JSON.parse(httpRequest.responseText);
				if (callbackFunction) {
					callbackFunction(data);
				}
			}
		}
	};
	httpRequest.open('GET', URL);
	httpRequest.send();
}

//Call function with arguments
makeAjaxRequest('https://dog.ceo/api/breeds/list/all', function (data) {
	console.log(data.message);
});

 

// Working with XML

var request;
if (window.XMLHttpRequest) {
	request = new XMLHttpRequest();
} else {
	request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET', 'data.xml');
request.onreadystatechange = function() {
	if ((request.readyState===4) && (request.status===200)) {
		console.log(request.responseXML.getElementsByTagName('name')[1].firstChild.nodeValue);
		
		var items = request.responseXML.getElementsByTagName('name');
		var output = '<ul>';
		for (var i = 0; i < items.length; i++) {
			output += '<li>' + items[i].firstChild.nodeValue + '</li>';
		}
		output += '</ul>';
		document.getElementById('update').innerHTML = output;
	}
}
request.send();
//Working with JSON

var mybutton = document.getElementById('loadbutton');
mybutton.onclick = function() {
   var request;
   if (window.XMLHttpRequest) {
      request = new XMLHttpRequest();
   } else {
      request = new ActiveXObject("Microsoft.XMLHTTP");
   }
   request.open('GET', 'data.json');
   request.onreadystatechange = function() {
      if ((request.readyState===4) && (request.status===200)) {
         var items = JSON.parse(request.responseText);
         var output = '<ul>';
         for (var key in items) {
            output += '<li>' + items[key].name + '</li>';
         }
         output += '</ul>';
         document.getElementById('update').innerHTML = output;
      }
   }
   request.send();
} // loadAJAX

 

 

XMLHttpRequest

2. October 2018

This is the simplest usage of asynchronous XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.open("GET", "/bar/foo.txt", true);
xhr.onload = function (e) {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      console.log(xhr.responseText);
    } else {
      console.error(xhr.statusText);
    }
  }
};
xhr.onerror = function (e) {
  console.error(xhr.statusText);
};
xhr.send(null);

 

A standard function to read external files:

function xhrSuccess() { 
    this.callback.apply(this, this.arguments); 
}

function xhrError() { 
    console.error(this.statusText); 
}

function loadFile(url, callback /*, opt_arg1, opt_arg2, ... */) {
    var xhr = new XMLHttpRequest();
    xhr.callback = callback;
    xhr.arguments = Array.prototype.slice.call(arguments, 2);
    xhr.onload = xhrSuccess;
    xhr.onerror = xhrError;
    xhr.open("GET", url, true);
    xhr.send(null);
}

Usage:

function showMessage(message) {
    console.log(message + this.responseText);
}

loadFile("message.txt", showMessage, "New message!\n\n");

 

Example: using a timeout:

function loadFile(url, timeout, callback) {
    var args = Array.prototype.slice.call(arguments, 3);
    var xhr = new XMLHttpRequest();
    xhr.ontimeout = function () {
        console.error("The request for " + url + " timed out.");
    };
    xhr.onload = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                callback.apply(xhr, args);
            } else {
                console.error(xhr.statusText);
            }
        }
    };
    xhr.open("GET", url, true);
    xhr.timeout = timeout;
    xhr.send(null);
}

Usage:

function showMessage (message) {
    console.log(message + this.responseText);
}

loadFile("message.txt", 2000, showMessage, "New message!\n");

Also a way of use:

var request = new XMLHttpRequest();
request.open('GET', 'https://api.cryptonator.com/api/ticker/btc-usd');
request.onreadystatechange = function () {
	if ((request.readyState === 4) && (request.status === 200)) {
		console.log(request);
		console.log(request.responseText);
	}
}
request.send();

 

 

Canvas

25. September 2018

A basic example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas</title>
</head>
<body>
<canvas id="canvas" style="border: 2px dotted gold; width: 100vw; height: 100vh"></canvas>
<script>
var canvas = document.getElementById("canvas");

if(canvas.getContext){
var ctx = canvas.getContext("2d");
ctx.fillRect(90,60,120,60); //X, Y, WIDTH, HEIGHT
}
else{
alert('Your browser doesn't support HTML canvas');
}
</script>
</body>
</html>

Examples of ‘command’:

ctx.fillStyle = "#FF0000";

//Rectangle
ctx.fillRect(0,0,150,75);

//Line
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();

//Circle
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();

//Create gradient
var grd=ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
//Fill with gradient
ctx.fillStyle=grd;
ctx.fillRect(10,10,150,80);

//Text
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50); //or ctx.strokeText("Hello World",10,50);
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Hello World", canvas.width/2, canvas.height/2);

//Image
var img = document.getElementById("scream"); //or url
ctx.drawImage(img, 10, 10);

 

 

 

Local Storage

22. September 2018

Live demo: https://thomasweb.studio/blueperu/

localStorage.setItem('Favorite Color', 'Blue');

localStorage.getItem('Favorite Color')

localStorage.clear();

 

Shadow DOM

18. September 2018

Example

HTML:

<div class="outer">
    <div id="shadowdom"></div>
    <div class="normalTree">
        Hello World, from the normal dom!
    </div>    
</div>

JS:

var shadowHost = document.querySelector("#shadowdom");
var shadowRoot = shadowHost.createShadowRoot();
shadowRoot.innerHTML = ["<div class='shadowChild'>",
                        "Inside the Shadow DOM:",
                        "<h2>Hello Shadow</h2>",
                        "</div>"
                        ];

Could also ‘grab’ the content from a <template> tag in the html document like this:

HTML:

<div id="shadowdom"></div>
<template id="template">
	<style> #text { color: gold; } </style>
	<p id="text">Hi from the shadow dom</p>
</template>
<div>
	<p id="text">Hi from the normal dom!</p>
</div>

JS:

var shadowHost = document.querySelector("#shadowdom");
var shadowRoot = shadowHost.createShadowRoot();
shadowRoot.appendChild(document.querySelector('#template').content);

 

 

Creating & removing HTML Elements (Nodes)

18. September 2018

Creating:

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);

var element = document.getElementById("div1");
element.appendChild(para);
</script>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);

var element = document.getElementById("div1");
var child = document.getElementById("p1");
element.insertBefore(para, child);
</script>
// Doesn't work in IE
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);

var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.replaceChild(para, child);
</script>

Removing:

<!--Sample HTML code-->

<div id="top">
  <div id="nested"></div>
</div>

// Removing a specified element when knowing its parent node
var d = document.getElementById("top");
var d_nested = document.getElementById("nested");
var throwawayNode = d.removeChild(d_nested);

// Removing a specified element without having to specify its parent node
var node = document.getElementById("nested");
if (node.parentNode) {
  node.parentNode.removeChild(node);
}

// Removing all children from an element
var element = document.getElementById("top");
while (element.firstChild) {
  element.removeChild(element.firstChild);
}

 

 

 

Data Attributes

18. September 2018

Attribute Name
The data attribute name must be at least one character long and must be prefixed with ‘data-‘. It should not contain any uppercase letters.

Attribute Value
The attribute value can be any string.

<ul id="vegetable-seeds">
  <li data-spacing="10cm" data-sowing-time="March to June">Carrots</li>
  <li data-spacing="30cm" data-sowing-time="February to March">Celery</li>
  <li data-spacing="32cm" data-sowing-time="March to September">Radishes</li>
</ul>

Set & get attribute

<div id='strawberry-plant' data-fruit='12'></div>

<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'

// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7');
</script>
Proper way:

<div id='sunflower' data-leaves='47' data-plant-height='2.4m'></div>

<script>
// 'Getting' data-attributes using dataset 
var plant = document.getElementById('sunflower');
var leaves = plant.dataset.leaves; // leaves = 47;

// 'Setting' data-attributes using dataset
var tallness = plant.dataset.plantHeight; // 'plant-height' -> 'plantHeight'
plant.dataset.plantHeight = '3.6m'; 
</script>

Remove the data attribute:

plant.dataset.leaves = null;

Select elements:

// Select all elements with a 'data-flowering' attribute
document.querySelectorAll('[data-flowering]');

// Select all elements with red leaves
document.querySelectorAll('[data-foliage-colour="red"]');

Dataset:

var restaurant = document.getElementById("restaurantId");

var ratings = restaurant.dataset.ratings;
restaurant.dataset.ratings = newRating;

var owner = restaurant.dataset['ownerName'];
restaurant.dataset['ownerName'] = 'newOwner';

 

 

Modifying the DOM

18. September 2018

// Find a style value of a element in dom
var header = document.querySelector('.header');
window.getComputedStyle(header).getPropertyValue('margin-left')

// Append element1 as the last child of element2
element1.appendChild(element2)

// Insert element2 as child of element 1, right before element3
element1.insertBefore(element2, element3)

// Gets the input submit
const myChildElemet = myElement.querySelector('input[type="submit"]')

// Create a clone
const myElementClone = myElement.cloneNode()
myParentElement.appendChild(myElementClone)

// Create new elements
const myNewElement = document.createElement('div')
const myNewTextNode = document.createTextNode('some text')

// Remove a child (workaround)
myElement.parentNode.removeChild(myElement)

// Replace the inner HTML
myElement.innerHTML = `
  <div>
    <h2>New content</h2>
    <p>beep boop beep boop</p>
  </div>
`

//Adds to the innerhtml
header.innerHTML += `
  <a href="foo.html">continue reading...</a>
  <hr/>
`

// Remove all child nodes
myElement.innerHTML = null

// Best way of listening for event
myElement.addEventListener('click', function (event) {
  console.log(event.type + ' got fired')
})

// Prevent default
myForm.addEventListener('submit', function (event) {
  const name = this.querySelector('#name')

  if (name.value === 'Donald Duck') {
    alert('You gotta be kidding!')
    event.preventDefault()
  }
})

//Classlist
node.classList.add(class) //adds a class
node.classList.remove(class)
node.classList.toggle(class)
node.classList.length //how many
node.classList.contains //class name


//insert html anywhere in the dom
myNode.insertAdjacentHTML('afterend','<p>This is added html to the end of whatever myNode is</p>') //Could be 'beforebegin' 'afterbegin' (after the first element), 'beforeend' (before the last element)
variable.setAttribute('id', 'ticket');
variable.placeholder = 'Symbol';
variable.style.width = '90%';
variable.innerHTML = 'USD';
variable.className = 'flex-container';
Check if body has a certain class

24. July 2018

var body = document.querySelector('body');

if (document.body.classList.contains('home')) {
	body.classList.remove('list-view');
	body.classList.add('grid-view');
}

if you dont get anything, make sure the script is loading after the dom content.

 

And with Jquery:
if ($("body").hasClass("home")) {
    //Do something
}
Connect to mySQL with node.js

7. July 2018

var mysql = require('mysql');

var con = mysql.createConnection({
	host: "localhost",
	port: "8889",
	user: "root",
	password: "root",
	database: "stoks"
});

con.connect(function (err) {
	if (err) throw err;
	console.log('Connected to DB');

	con.query("SELECT * FROM stok ORDER BY symbol", function (err, result) {
		if (err) throw err;
		console.log(result);
	});
});

con.end();

 

Scroll effect JavaScript

9. June 2018

/**
 * Scroll effect
 */

function scrolly() {
	var ecapsx1 = document.getElementById('ecapsx1');
	var ypos    = window.pageYOffset;

	if (ypos < 1) {
		ecapsx1.classList.add('bounceInDown');
		ecapsx1.classList.remove('bounceOutUp');
	}

	if (ypos > 10) {
		ecapsx1.classList.add('bounceOutUp');
	}

	if (ypos > 328) {
		ecapsx1.classList.add('bounceInDown');
		ecapsx1.classList.remove('bounceOutUp');
	}

	console.log(ypos);
}

window.addEventListener("scroll", scrolly);

 

Fetching Api using vanilla JavaScript vs jQuery

28. May 2018

JavaScript:

	fetch('https://api.magicthegathering.io/v1/cards')
		.then(result => result.json())
		.then((res) => { createCard(res); })
		.catch(err => console.log(err))

	var myCards = document.getElementById('cards');

	function createCard(result) {
		var myCard = result['cards'];

		//some output can go here
		
		}
	}

jQuery:

	$.getJSON('https://api.spacexdata.com/v2/launches/next', function(data) {
		var launch_date_utc = data['launch_date_utc'];
		$('#next-launch').html(launch_date_utc);
	});

 

Add touch events

22. May 2018

function addListeners() {
	document.querySelectorAll(".flip-container").forEach(function(elem) {
		elem.addEventListener("touchstart", function() {
			flipContainer.classList.toggle('trigger');
		});
	});
}
addListeners();