Document ready
$(document).ready(function () { //document is ready } //and $(function(){ //document is ready });
|
document.addEventListener("DOMContentLoaded", function(){ // });
|
//by id
$('#myId').onclick(function(e) {});
//by class
$('.myClass').hide();
|
//by id document.getElementById('myId').addEventListener("click", function() {}); document.querySelector('#myId'); //also works //by class - first only document.querySelector('.myClass'); //by class - nodeList var list = document.querySelectorAll('.myClass'); for ( var i = 0, var len = list.length; i < len; i++ ) { console.log(list[i]); } //pseudo selectors - find which radio checked var value = document.querySelector('input[name="pick"]:checked').value;
|
//classes $('#id').addClass('red'); $('#id').removeClass('green'); $('#id').toggleClass('yellow');
|
//IE10+ document.querySelector('#myId').classList.add('red'); document.querySelector('#myId').classList.remove('green'); document.querySelector('#myId').classList.toggle('yellow');
|
//events can be added to a group $('.allButtons').onclick(function(e) {});
|
//add events individually (or parent) document.querySelector('#myId').addEventListener('click', function(e) {}); //or parent var ehandler= function(e) { var target = event.target; if (target.hasAttribute('x')) { e.preventDefault(); //do something } }; document.addEventListener('click', ehandler);
|
//using XMLHttpRequest $.ajax({ url: "/Notifications", method:"POST", data: JSON.stringify({ href: location.href}), contentType: "application/json; charset=utf-8", success: function (data) { console.log(data.Count.length); }, error: function (e, textStatus, errorThrown) { //500 etc console.log(e.status + " status text=" + e.statusText + " error=" + errorThrown); } });
|
fetch("/Notifications", { method: 'POST', mode: 'cors', credentials: 'include', //by default it doesn't send auth cookies... headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ href: location.href }) //matching header }) //returns a response stream, so turn it into .json() .then((response) => { if (!response.ok) { throw new Error(response.url + " returned " + response.status); } return response.json(); }) .then((json) => { console.log(json.Count.length); }) .catch ((e) => { console.log(e.message); });
NOT any version of IE!
MDN
|