### Send GET Request with Fetch Source: https://speedsheet.io/s/javascript Initiates a GET request to a specified URL using the Fetch API. Can be used with async/await or Promises. ```javascript await fetch(url); ``` ```javascript response = await fetch(url); ``` ```javascript fetch(url) .then(response => {...}); ``` -------------------------------- ### Multiline String Example Source: https://speedsheet.io/s/javascript?q=String+Template+Literals Demonstrates creating a multiline string literal. ```javascript `This is on multiple lines!` ``` -------------------------------- ### Enable Debugger Source: https://speedsheet.io/s/javascript?q=debugger-only Starts the debugger in your browser. Place `debugger;` at the desired breakpoint. ```javascript debugger; ``` -------------------------------- ### Get Full URL Source: https://speedsheet.io/s/javascript Retrieves the complete URL string. ```javascript var url = new URL("https://speedsheet.io/s/http?q=data+types"); console.log(url.href); ``` -------------------------------- ### JavaScript Drag and Drop - Drag Start Event Source: https://speedsheet.io/s/javascript?q=event-types-only Fires when a user starts dragging an item. ```javascript element_1.addEventListener("dragstart", (event => {...})); ``` -------------------------------- ### JavaScript DocString Example Source: https://speedsheet.io/s/javascript DocStrings in JavaScript are multi-line comments that start with a forward slash followed by two asterisks. ```javascript /** * This is a doc string. */ function someFunction1() { ... } ``` -------------------------------- ### Get Operating System Platform Source: https://speedsheet.io/s/javascript?q=colors-only Returns a string identifying the user's operating system and platform. ```javascript = navigator.platform ``` -------------------------------- ### Get URL Host Source: https://speedsheet.io/s/javascript Retrieves the host name from a URL. ```javascript var url = new URL("https://speedsheet.io/s/http?q=data+types"); console.log(url.host); ``` -------------------------------- ### Check if String Starts With Prefix Source: https://speedsheet.io/s/javascript Checks if a string begins with the characters of a specified string. ```javascript string1.startsWith(start) ``` -------------------------------- ### Define a Class with Properties and Methods Source: https://speedsheet.io/s/javascript A detailed example of defining a class with an initial property value, a constructor, and methods that utilize instance properties. ```javascript class Class1 { property1 = initialValue; constructor(param1, param2) { this.property1 = param1; } method1(param1, param2) { return value; } method2() { value = this.property1; this.proprty1 = new_value; this.method1(...); } } ``` -------------------------------- ### Define Static Initialization Block Source: https://speedsheet.io/s/javascript?q=class-only Use a static initialization block for complex static setup logic within a class. ```javascript class Class1 { static { // Place static initialization code here. } } ``` -------------------------------- ### Get URL Protocol and Host Source: https://speedsheet.io/s/javascript Retrieves the protocol and host portion of the current URL. ```javascript location.origin ``` -------------------------------- ### Get URL Protocol Source: https://speedsheet.io/s/javascript Retrieves the protocol (e.g., 'http:', 'https:') from a URL. ```javascript var url = new URL("https://speedsheet.io/s/http?q=data+types"); console.log(url.protocol); ``` -------------------------------- ### JavaScript Nullish Coalescing Examples Source: https://speedsheet.io/s/javascript?q=Nullish+Coalescing Demonstrates the behavior of the nullish coalescing operator with string and null values. ```javascript console.log('value-1' ?? 'value-2'); // Prints: 'value-1' ``` ```javascript console.log(null ?? 'value-2'); // Prints: 'value-2' ``` -------------------------------- ### For Loop in Range Source: https://speedsheet.io/s/javascript Iterates from a start value up to, but not including, an end value. ```javascript for (const i = start; i < end_plus_one; i++) { ... } ``` -------------------------------- ### Get String Length Source: https://speedsheet.io/s/javascript Returns the number of characters in a string. ```javascript string1.length ``` -------------------------------- ### Get URL Parameters Source: https://speedsheet.io/s/javascript Retrieves the query string parameters from the current URL. ```javascript location.search ``` ```javascript window.location.search ``` -------------------------------- ### Get Class Name Source: https://speedsheet.io/s/javascript Retrieves the name of the class for a given instance. ```javascript = item1.constructor.name ``` -------------------------------- ### Get Response JSON Source: https://speedsheet.io/s/javascript Parses the response body as JSON using response.json(). ```javascript = await response.json() ``` ```javascript fetch (url) .then(response => { json = response.json() } ``` -------------------------------- ### Get URL Path Source: https://speedsheet.io/s/javascript Retrieves the path portion of the current URL, including any parameters. ```javascript location.pathname ``` ```javascript window.location.pathname ``` -------------------------------- ### Guard Clause Example Source: https://speedsheet.io/s/javascript Demonstrates using an 'if' statement without braces for a single-statement guard clause to handle invalid input early. ```javascript function do_something(value) { if (! value) // Guards against empty values. return; ... } ``` -------------------------------- ### Instantiate Basic Class Source: https://speedsheet.io/s/javascript?q=class-only Shows how to create an instance of a basic class and call its methods and access its properties. ```javascript item1 = new Class1(param1, param2); item1.method1(...); ... = item1.property1 ``` -------------------------------- ### Get Base URL Source: https://speedsheet.io/s/javascript Retrieves the base URL of the current web page, including the protocol and hostname. ```javascript window.location.protocol + "//" + window.location.hostname ``` -------------------------------- ### Get UTC Date Day Source: https://speedsheet.io/s/javascript?q=date-only Retrieves the day of the month according to UTC. ```javascript date1.getUTCDate() ``` -------------------------------- ### Create an Array with Initial Values Source: https://speedsheet.io/s/javascript?q=array-only Shows how to create an array and populate it with initial values. ```javascript = [value1, value2, ...] ``` ```javascript = new Array(value1, value2, ...) ``` -------------------------------- ### Get Response Text Source: https://speedsheet.io/s/javascript Retrieves the response body as plain text using response.text(). ```javascript = await response.text() ``` ```javascript fetch (url) .then(response => { text = response.text() } ``` -------------------------------- ### Get Element Class Name Source: https://speedsheet.io/s/javascript?q=Element-Only Access the `className` property to get a space-separated string of all classes assigned to an element. ```javascript element1.className; ``` -------------------------------- ### Instantiate a Class with Constructor Arguments Source: https://speedsheet.io/s/javascript Shows how to create a new class instance, passing arguments to the constructor to initialize the object's state. ```javascript let item1 = new Class1(param1, param2); ``` -------------------------------- ### Get URL Query String Source: https://speedsheet.io/s/javascript Retrieves the entire query string of a URL, including the leading question mark. ```javascript var url = new URL("https://speedsheet.io/s/http?q=data+types"); console.log(url.search); ``` -------------------------------- ### Simulate Queue with Array Source: https://speedsheet.io/s/javascript Demonstrates how to use a JavaScript array to simulate queue behavior using push (enqueue) and shift (dequeue). ```javascript let queue1 = []; queue1.push(1); queue1.push(2); queue1.push(3); let next = queue1.shift(); console.log(next); // Prints: 1 ``` -------------------------------- ### Get a Value from a Map Source: https://speedsheet.io/s/javascript Retrieve the value associated with a given key from a Map using the `get()` method. Returns `undefined` if the key is not found. ```javascript map1.get(key); ``` -------------------------------- ### Getting Local Storage Key by Index Source: https://speedsheet.io/s/javascript Retrieves the key name at a specific index from local storage. ```javascript localStorage.key(index); ``` -------------------------------- ### Get First Child Element Source: https://speedsheet.io/s/javascript?q=Element-Only Use `firstElementChild` to get the first child that is an element node. Returns `null` if no element children are found. ```javascript element1.firstElementChild; ``` -------------------------------- ### Get Key by Index in Session Storage Source: https://speedsheet.io/s/javascript Retrieves the key at a specific index within the session storage. ```javascript sessionStorage.key(index); ``` -------------------------------- ### Get All Child Elements Source: https://speedsheet.io/s/javascript?q=Element-Only Access the `children` property to get an HTMLCollection of all direct child elements of a given element. This excludes text nodes and comments. ```javascript element1.children; ``` -------------------------------- ### Create an Empty Array Source: https://speedsheet.io/s/javascript?q=array-only Demonstrates multiple ways to initialize an empty array in JavaScript. ```javascript = [] ``` ```javascript = new Array() ``` -------------------------------- ### Start Async Function from Non-Async Context (Promise Chaining) Source: https://speedsheet.io/s/javascript?q=async-only Initiates an asynchronous operation from a non-async function by directly calling the async function and using promise chaining (.then/.catch). This is an alternative to IIFE for handling the result or errors. ```javascript function_1() .then(success_function) .catch((error) => {...}) ``` -------------------------------- ### Define and Instantiate a Basic Class Source: https://speedsheet.io/s/javascript?q=class-only Defines a class with a property, constructor, and methods, and then instantiates it. Use this for general class definitions. ```javascript class Class1 { property1 = initialValue; constructor(param1, param2) { this.property1 = param1; } method1(param1, param2) { return value; } method2() { value = this.property1; this.proprty1 = new_value; this.method1(...); } } ``` ```javascript let item1 = new Class1(param1, param2); ``` -------------------------------- ### Get and Set Element Value Source: https://speedsheet.io/s/javascript?q=Element-Only The `value` property is used for form elements like input fields to get or set their current value. Changes to this property can update the element's displayed value. ```javascript element1.value; ``` -------------------------------- ### Pad String Start or End Source: https://speedsheet.io/s/javascript Adds padding to the beginning or end of a string until it reaches a specified length. Padding can be a string or omitted. ```javascript string1.padStart(length) ``` ```javascript string1.padStart(length, padding) ``` ```javascript string1.padEnd(length) ``` ```javascript string1.padEnd(length, padding) ``` -------------------------------- ### Get URL Pathname Source: https://speedsheet.io/s/javascript Retrieves the pathname component of a URL. ```javascript var url = new URL("https://speedsheet.io/s/http?q=data+types"); console.log(url.pathname); ``` -------------------------------- ### Get URL Hash / Path Fragment Source: https://speedsheet.io/s/javascript Retrieves the hash fragment (e.g., '#section') from the current URL. ```javascript location.hash ``` ```javascript window.location.hash ``` -------------------------------- ### Promise - Basic Creation Source: https://speedsheet.io/s/javascript Create a new Promise with a function that takes resolve and reject callbacks. Use resolve for success and reject for failure. ```javascript var promise1 = new Promise( (resolve, reject) => { ... resolve(successful_response) ... reject(failed_response) }); ``` -------------------------------- ### Start Async Function from Non-Async Context (IIFE) Source: https://speedsheet.io/s/javascript?q=async-only Initiates an asynchronous operation from a non-async function using an Immediately Invoked Function Expression (IIFE). This allows top-level await-like behavior. ```javascript (async () => { await function_1(); })(); ``` -------------------------------- ### Create an Array using new Array() Source: https://speedsheet.io/s/javascript Instantiate an array using the Array constructor. ```javascript new Array() ``` ```javascript new Array(value1, value2, ...) ``` -------------------------------- ### Get Seconds Source: https://speedsheet.io/s/javascript?q=date-only Retrieves the seconds (0-59) from a Date object. ```javascript date1.getSeconds() ``` -------------------------------- ### Drag and Drop Events Source: https://speedsheet.io/s/javascript This section covers drag and drop events such as 'drop', 'dragstart', 'dragend', 'dragenter', and 'dragleave'. It also details properties like 'dropEffect' and 'files'. ```APIDOC ## Drag and Drop Event - Drop ### Description Fires when a user drops an item on a drop target. ### Usage `element_1.addEventListener("drop", (event => {...}));` ### Event Data - **event.dataTransfer.files** (FileList) - The files associated with the drop event. ``` ```APIDOC ## Drag and Drop Event - Start ### Description Fires when a user starts dragging an item. ### Usage `element_1.addEventListener("dragstart", (event => {...}));` ``` ```APIDOC ## Drag and Drop Event - End ### Description Fires when a user stops dragging an item. This event always fires, regardless of whether the drop was completed or canceled. ### Usage `element_1.addEventListener("dragend", (event => {...}));` ``` ```APIDOC ## Drag and Drop Event - Enter Drop Target ### Description Fires when a user moves a dragged item into a valid drop target area. ### Usage `element_1.addEventListener("dragenter", (event => {...}));` ``` ```APIDOC ## Drag and Drop Event - Leave Drop Target ### Description Fires when a user moves a dragged item out of a valid drop target area. ### Usage `element_1.addEventListener("dragleave", (event => {...}));` ``` ```APIDOC ## Drag and Drop Event Property - Drop Effect ### Description Sets the visual feedback for the drop operation by changing the cursor. ### Usage `event_1.dataTransfer.dropEffect = 'effect'` ### Possible Effects - **'copy'**: Indicates a copy operation. On Mac, displays a Plus Sign. - **'move'**: Indicates a move operation. On Mac, displays a File Icon. ``` ```APIDOC ## Drag and Drop Event Property - Drop Files ### Description Retrieves the files that were dropped during a drop event. ### Usage `event.dataTransfer.files` ### Returns - **FileList**: A FileList object containing the dropped files. ``` -------------------------------- ### Get Minutes Source: https://speedsheet.io/s/javascript?q=date-only Retrieves the minutes (0-59) from a Date object. ```javascript date1.getMinutes() ``` -------------------------------- ### Get Milliseconds Source: https://speedsheet.io/s/javascript?q=date-only Retrieves the milliseconds (0-999) from a Date object. ```javascript date1.getMilliseconds() ``` -------------------------------- ### Instantiate a Class Source: https://speedsheet.io/s/javascript Creates a new object instance from a defined class. Methods and properties can then be accessed using the instance. ```javascript item1 = new Class1(param1, param2); item1.method1(...); ... = item1.property1 ``` -------------------------------- ### Handle Key Up Event and Get Key Information Source: https://speedsheet.io/s/javascript?q=event-types-only Use the 'keyup' event to detect when a key is released. Access event.key for the key identifier or event.keyCode/event.which (deprecated) for the key code. ```javascript document.addEventListener('keyup', function1); element1.addEventListener('keyup', function1); // Get Key: // = event.key if (event.key === 'Escape') ... ``` ```javascript // Get Key Code (Deprecated): // = event.keyCode | event.which ``` -------------------------------- ### Get Hours Source: https://speedsheet.io/s/javascript?q=date-only Retrieves the hour (0-23) from a Date object. ```javascript date1.getHours() ``` -------------------------------- ### Create Strings Source: https://speedsheet.io/s/javascript Demonstrates the creation of string literals using both single and double quotes. Both methods are interchangeable for simple strings. ```javascript 'A String' ``` ```javascript "A String" ``` ```javascript "Join " + "Strings " + "Together" ``` -------------------------------- ### Get Array Length Source: https://speedsheet.io/s/javascript?q=array-only Retrieves the number of elements in an array. ```javascript = array1.length ``` -------------------------------- ### Instantiate Class Source: https://speedsheet.io/s/javascript?q=class-only Create a new object instance from a class definition using the `new` keyword. ```javascript new Class1(); ``` -------------------------------- ### Create an Array with Values Source: https://speedsheet.io/s/javascript Initialize an array with one or more values separated by commas. ```javascript [value1, value2, ...] ``` -------------------------------- ### Get Set Size Source: https://speedsheet.io/s/javascript Returns the number of elements currently in the Set. ```javascript set1.size; ``` -------------------------------- ### Promise - Basic Usage Source: https://speedsheet.io/s/javascript Handle Promise fulfillment and rejection using .then() and .catch() methods. Chaining multiple .then() calls is supported. ```javascript var result1 = () => { promise1 .then((fulfilled) => { ... }) .catch((error) => { ... }) }; ``` ```javascript var result1 = promise1 .then(...) .then(...) .then(...) .catch(...); // Catch All Errors ``` ```javascript var result1 = promise1 .then(...) .catch(...) // Catch Errors From 1st then() .then(...) .catch(...) // Catch Errors From 2nd then() ... ``` -------------------------------- ### Get Date Day Source: https://speedsheet.io/s/javascript?q=date-only Retrieves the day of the month from a Date object. ```javascript date1.getDate() ``` -------------------------------- ### Importing All from a Module Source: https://speedsheet.io/s/javascript Import all exports from a module using the '*' syntax. Note: This specific syntax might have limitations or require specific module configurations. ```javascript import * from "file_name.mjs" ``` -------------------------------- ### Promise - Define with Parameters Source: https://speedsheet.io/s/javascript Define a Promise constructor that accepts parameters using closures to pass values into the Promise's execution context. ```javascript function newPromise1(param1, param2, ...) { return new Promise((resolve, reject) => { ... }) } ``` -------------------------------- ### Initialize a Set Source: https://speedsheet.io/s/javascript Create a new Set, optionally initializing it with values from an iterable. ```javascript const mySet = new Set(); ``` ```javascript const mySetWithValues = new Set([value1, value2]); ``` -------------------------------- ### Open URL in New Window Source: https://speedsheet.io/s/javascript Opens a specified URL in a new browser window. ```javascript window.open("url") ``` ```javascript window.open("https://speedsheet.io/"); ``` -------------------------------- ### Get Response Status Code Source: https://speedsheet.io/s/javascript Retrieves the HTTP status code of the response. ```javascript = response.status ``` -------------------------------- ### JavaScript Associative Array Initialization Source: https://speedsheet.io/s/javascript?q=associative-array-only Demonstrates two ways to initialize an associative array (object) in JavaScript: an empty object and an object with initial key-value pairs. ```javascript = {} ``` ```javascript = {"key1":value1, "key2":value2, ...} ``` -------------------------------- ### Check if URL Parameter Exists Source: https://speedsheet.io/s/javascript Tests if a URL query parameter exists and has a value. Uses `get()` which returns null for non-existent parameters. ```javascript var url = new URL("https://speedsheet.io/s/http?q=data+types"); if (url.searchParams.get('search')) { console.log('search = ', url.searchParams.get('search')); } else { console.log('search does not exist.'); } ``` -------------------------------- ### JavaScript Associative Array - Get Value by Key Source: https://speedsheet.io/s/javascript?q=associative-array-only Demonstrates how to access the value associated with a specific key in a JavaScript associative array. ```javascript = array1["key1"] ``` -------------------------------- ### Show an element Source: https://speedsheet.io/s/javascript?q=Element-Only Set the element's `display` style property to 'block' (or an appropriate value) to make it visible. ```javascript element1.style.display = 'block'; ``` -------------------------------- ### Get and Set Element Width Source: https://speedsheet.io/s/javascript?q=Element-Only Control an element's width via the `style.width` property. `clientWidth` returns content width plus padding, while `offsetWidth` includes content, padding, and border. ```javascript element1.style.width; ``` ```javascript element1.style.width = ...; ``` ```javascript element1.clientWidth; ``` ```javascript element1.offsetWidth; ``` -------------------------------- ### Get URL Hash (Fragment) Source: https://speedsheet.io/s/javascript Retrieves the fragment identifier (the part after '#') from a URL. ```javascript var url = new URL("https://speedsheet.io/s/java#45aB"); console.log(url.hash); ``` -------------------------------- ### Create a Map Source: https://speedsheet.io/s/javascript Initialize a new Map object. Maps can be created empty or populated with an iterable of key-value pairs. ```javascript new Map(); ``` ```javascript new Map([[key1, value1], [key2, value2], ...]) ``` -------------------------------- ### Create Multiline Strings Source: https://speedsheet.io/s/javascript Shows how to create strings that span multiple lines using single quotes with escaped newlines, double quotes with escaped newlines, or template literals. ```javascript 'A multiline\n string.' ``` ```javascript "A multiline\n string." ``` ```javascript `A multiline string.` ``` -------------------------------- ### Get All Elements by Class Name Source: https://speedsheet.io/s/javascript?q=Element-Only Returns a live HTMLCollection of all elements in the document that have the specified class name. Returns an empty collection if no elements are found. ```javascript document.getElementsByClassName('class') ``` -------------------------------- ### Access Static Members Source: https://speedsheet.io/s/javascript?q=class-only Demonstrates how to access static methods and properties of a class using the class name. ```javascript Class1.method1(...); ... = Class1.property1 ``` -------------------------------- ### Call Async Functions in Series Source: https://speedsheet.io/s/javascript?q=async-only Executes multiple asynchronous functions sequentially, awaiting the completion of each one before starting the next. This ensures operations happen in a specific order. ```javascript await function1(); await function2(); await function3(); ``` -------------------------------- ### Element - Child Elements - Get First By Selector Source: https://speedsheet.io/s/javascript?q=Element-Only Returns the first child element that matches the provided CSS selector. The selector can be any valid CSS selector. ```APIDOC ## Element - Child Elements - Get First By Selector ### Description Returns the first child element that matches the provided CSS selector. The selector can be any valid CSS selector. ### Method ```javascript parentElement.querySelector('selector'); ``` ``` -------------------------------- ### Listen for Media Query Changes Source: https://speedsheet.io/s/javascript?q=colors-only Adds a listener to detect when a media query (e.g., screen size) changes its state. ```javascript var mediaQuery = window.matchMedia("media-break"); mediaQuery.addEventListener("change", mediaQueryListener); ``` ```javascript function mediaQueryListener(change) { if(change.matches) { // Switched to media break. } else { // Switched from media break. } } ``` ```javascript function mediaQueryListener(change) { if(change.matches) { console.log("Resolution now >= 576"); } else { console.log("Resolution now < 576"); } } var mediaQuery = window.matchMedia("(min-width: 576px)"); mediaQuery.addEventListener("change", mediaQueryListener); ``` -------------------------------- ### Get Response Form Data Source: https://speedsheet.io/s/javascript Retrieves the response body as FormData using response.formData(). ```javascript = await response.formData() ``` ```javascript fetch (url) .then(response => { formData = response.formData() } ``` -------------------------------- ### Get and Set Element Height Source: https://speedsheet.io/s/javascript?q=Element-Only Manipulate the `style.height` property to set an element's height. Use `clientHeight` for content height plus padding, and `offsetHeight` for content height plus padding and border. ```javascript element1.style.height; ``` ```javascript element1.style.height = ...; ``` ```javascript element1.clientHeight; ``` ```javascript element1.offsetHeight; ``` -------------------------------- ### Create Date with Year, Month, Day Source: https://speedsheet.io/s/javascript?q=date-only Creates a date object with the specified year, month, and day. Hour, minute, and second are set to 0. ```javascript new Date(year, month, day) ``` -------------------------------- ### Get All Values from a Map Source: https://speedsheet.io/s/javascript Retrieve an iterator for all values in a Map using the `values()` method. ```javascript map1.values() ``` -------------------------------- ### Get All Keys from a Map Source: https://speedsheet.io/s/javascript Retrieve an iterator for all keys in a Map using the `keys()` method. ```javascript map1.keys() ``` -------------------------------- ### Create Date with Year, Month, Day, Hour, Minute, Second Source: https://speedsheet.io/s/javascript?q=date-only Creates a date object with the specified year, month, day, hour, minute, and second. ```javascript new Date(year, month, day, hour, minute, second) ``` -------------------------------- ### Handle Key Press Event and Get Key Information Source: https://speedsheet.io/s/javascript?q=event-types-only The 'keypress' event captures character-producing key presses. Use event.key for the key name or event.keyCode/event.which (deprecated) for the key code. ```javascript document.addEventListener('keypress', function1); element1.addEventListener('keypress', function1); // Get Key: // = event.key if (event.key === 'Escape') ... ``` ```javascript // Get Key Code (Deprecated): // = event.keyCode | event.which ``` -------------------------------- ### Get Text Input Value Source: https://speedsheet.io/s/javascript?q=Element-Only Retrieve the current value of a text input element. ```javascript element1.value ``` -------------------------------- ### Link to JavaScript Function Source: https://speedsheet.io/s/javascript Create a hyperlink that executes JavaScript code when clicked. ```html ... ``` ```html Show Alert ``` -------------------------------- ### Get Checkbox State Source: https://speedsheet.io/s/javascript?q=Element-Only Retrieve the current checked state of an input checkbox element. ```javascript element1.checked ``` -------------------------------- ### Open URL in New Window with Dimensions Source: https://speedsheet.io/s/javascript Opens a specified URL in a new browser window and sets its dimensions (width and height). ```javascript window.open("url", "", "width=width, height=height") ``` ```javascript window.open("https://speedsheet.io", "", "width=1024, height=640"); ``` -------------------------------- ### Get Element ID Source: https://speedsheet.io/s/javascript?q=Element-Only Retrieve the unique identifier of an element using its `id` property. ```javascript element1.id; ``` -------------------------------- ### Iterate Over Set Elements Source: https://speedsheet.io/s/javascript Demonstrates iterating over the elements of a Set using a for...in loop. Note: for...in is generally not recommended for Sets; for...of is preferred. ```javascript for (const item in set1) { ... } ``` -------------------------------- ### Handle Key Down Event and Get Key Information Source: https://speedsheet.io/s/javascript?q=event-types-only Listen for the 'keydown' event to capture key presses. Access event.key for the key identifier or event.keyCode/event.which (deprecated) for the key code. ```javascript document.addEventListener('keydown', function1); element1.addEventListener('keydown', function1); // Get Key: // = event.key if (event.key === 'Escape') ... ``` ```javascript // Get Key Code (Deprecated): // = event.keyCode | event.which ``` -------------------------------- ### Get Full Year Source: https://speedsheet.io/s/javascript?q=date-only Retrieves the full year (e.g., 2023) from a Date object. ```javascript date1.getFullYear() ``` -------------------------------- ### Getting Local Storage Size Source: https://speedsheet.io/s/javascript Returns the number of items currently stored in local storage. ```javascript localStorage.length ``` -------------------------------- ### Send PUT Request with Fetch Source: https://speedsheet.io/s/javascript Initiates a PUT request to a specified URL using the Fetch API. ```javascript fetch (url, { method: 'PUT', ... }) ``` -------------------------------- ### Assign and Compare Enum Value (Object) Source: https://speedsheet.io/s/javascript?q=enum-only Demonstrates how to assign a value from an object-based enum and compare it. ```javascript var shape1 = Shape.circle = shape1 === Shape.circle ``` -------------------------------- ### Get URL Without Parameters Source: https://speedsheet.io/s/javascript Constructs the current URL string excluding any query parameters. ```javascript window.location.href.split('?')[0] ``` -------------------------------- ### Iterate with forEach Source: https://speedsheet.io/s/javascript?q=array-only Executes a provided function once for each array element. Iteration with index is also supported. ```javascript array1.forEach(item => {...}); ``` ```javascript array1.forEach(item, index => {...}); ``` -------------------------------- ### Get Shadow DOM Inner HTML Source: https://speedsheet.io/s/javascript Retrieves the inner HTML content of the shadow root. ```javascript element1.shadowRoot.innerHTML ``` -------------------------------- ### Get Character at Position Source: https://speedsheet.io/s/javascript Retrieves the character at a specific index within a string. Indices are zero-based. ```javascript string1.charAt(position) ``` ```javascript char2 = "012345".charAt(2); // Returns "2" ``` -------------------------------- ### Create an Empty Array Source: https://speedsheet.io/s/javascript Use square brackets to create an empty array. ```javascript [] ``` -------------------------------- ### Element - Scroll To Top Source: https://speedsheet.io/s/javascript?q=Element-Only Gets or sets the scroll position of the element's content to the top. ```APIDOC ## Element - Scroll To Top ### Description Gets or sets the scroll position of the element's content to the top. ### Property ```javascript element1.scrollTop; ``` ``` -------------------------------- ### JavaScript Console Dir Source: https://speedsheet.io/s/javascript?q=console-only Use console.dir to print a formatted object or element to the console. ```javascript console.dir(item); ``` -------------------------------- ### Define Object with Constructor Function Source: https://speedsheet.io/s/javascript Define a constructor function using `function` and `this` to set properties and methods. Instantiate with the `new` keyword. ```javascript function ObjectName(param1, param2, ...) { this.property1 = value1; this.property2 = value2; this.method1 = function(){ ... } } = new ObjectName(param1, param2); ``` -------------------------------- ### Define a Class Constructor Source: https://speedsheet.io/s/javascript?q=class-only Specifies the constructor for a class. Use this when you need to explicitly define how a class instance is initialized. ```javascript class Class1 { constructor(param1, param2) { ... } } ``` ```javascript let item1 = new Class1(param1, param2); ``` -------------------------------- ### Importing Specific Module Functions Source: https://speedsheet.io/s/javascript Import specific functions or variables from a module using curly braces. Ensure the file has the '.js' extension and 'type: "module"' is set in package.json for this to work. ```javascript import {function1, function2, ...} from "file_name" ``` ```javascript import {function1, function2, ...} from "file_name.mjs" ``` -------------------------------- ### Get Element Offset Width Source: https://speedsheet.io/s/javascript Retrieve the width of an element, including padding and border, using `offsetWidth`. ```javascript element1.offsetWidth; ``` -------------------------------- ### Accessing Document Properties Source: https://speedsheet.io/s/javascript Demonstrates how to access the document's title and body. The `document.title` can also be updated. ```javascript let pageTitle = document.title; ``` ```javascript let pageBody = document.body; ``` -------------------------------- ### Get Element Offset Height Source: https://speedsheet.io/s/javascript Retrieve the height of an element, including padding and border, using `offsetHeight`. ```javascript element1.offsetHeight; ``` -------------------------------- ### Bind Function to Class Instance Source: https://speedsheet.io/s/javascript?q=class-only Demonstrates binding a class method to its instance. This is crucial for callbacks where `this` context might be lost. ```javascript item1.function1.bind(itemToBeBoundTo); this.function1.bind(this); ``` ```javascript class Class1 { callback1() { this.... } getCallback() { return this.callback1.bind(this); } } // In Use: let callback = instance1.getCallback(); callback(); ``` -------------------------------- ### Get Month Source: https://speedsheet.io/s/javascript?q=date-only Retrieves the month (0-11) from a Date object. Note that January is 0 and December is 11. ```javascript date1.getMonth() ``` -------------------------------- ### Get Day of Week Source: https://speedsheet.io/s/javascript?q=date-only Retrieves the day of the week (0 for Sunday, 6 for Saturday) from a Date object. ```javascript date1.getDay() ``` -------------------------------- ### Promise - Define and Resolve Source: https://speedsheet.io/s/javascript Instantiate a Promise, providing logic to resolve on success or reject on failure. Promises are evaluated eagerly. ```javascript new Promise((resolve, reject) => { ... //1 resolve(success_response) //2 reject(failed_response) //3 }) ``` -------------------------------- ### Get Sublist from Array Source: https://speedsheet.io/s/javascript?q=array-only Extracts a section of an array and returns a new array containing the selected elements. ```javascript array1.slice(start) ``` ```javascript array1.slice(start, end) ``` -------------------------------- ### Get Last Array Element Source: https://speedsheet.io/s/javascript?q=array-only Retrieves the last element of an array. Returns undefined if the array is empty. ```javascript = array1[array1.length - 1] ``` -------------------------------- ### Print Current Page Source: https://speedsheet.io/s/javascript?q=colors-only Opens the browser's print dialog to print the current web page. ```javascript window.print() ``` -------------------------------- ### Get First Array Element Source: https://speedsheet.io/s/javascript?q=array-only Retrieves the first element of an array. Returns undefined if the array is empty. ```javascript = array1[0] ``` -------------------------------- ### Handle Touch Up Event Source: https://speedsheet.io/s/javascript?q=event-types-only Listen for the 'touchup' event to detect when a touch point is removed from the screen over an element or the document. ```javascript document.addEventListener('touchup', function1); element1.addEventListener('touchup', function1); ``` -------------------------------- ### Set URL as New Page Source: https://speedsheet.io/s/javascript Updates the browser's URL and adds a new entry to the history, simulating navigation to a new page. Allows for back navigation to the previous state. ```javascript history.pushState ({}, '', url); ``` ```javascript history.pushState ({page: page_state}, title, url); ``` ```javascript window.history.pushState ({page: page_state}, title, url); ``` -------------------------------- ### Element - Set Text Source: https://speedsheet.io/s/javascript?q=Element-Only Changes the text content of an element. Provides an example of updating text content. ```APIDOC ## Element - Set Text ### Description Changes the text content of an element. Provides an example of updating text content. ### Method ```javascript element1.textContent = "text"; ``` ### Example ```html
``` ``` -------------------------------- ### Get Element Client Width Source: https://speedsheet.io/s/javascript Retrieve the inner width of an element, including padding but not the border, using `clientWidth`. ```javascript element1.clientWidth; ``` -------------------------------- ### Convention for Single Parameter Functions Source: https://speedsheet.io/s/javascript Demonstrates the conventional use of '_' as a parameter name for single-parameter anonymous functions. This is a stylistic choice, not a compiler-enforced rule. ```javascript const some_function = _ => {...}; const some_function = param1 => {...}; const log_the_argument = _ => { console.log("The Argument Is '" + _ + "'"); }; log_the_argument ("one"); ``` -------------------------------- ### Get Element Client Height Source: https://speedsheet.io/s/javascript Retrieve the inner height of an element, including padding but not the border, using `clientHeight`. ```javascript element1.clientHeight; ``` -------------------------------- ### Continue With Label Source: https://speedsheet.io/s/javascript?q=control-structure-only Skips to the next iteration of a labeled loop. ```javascript label_name: ... continue label_name; ``` -------------------------------- ### Get Object Property Names Source: https://speedsheet.io/s/javascript Retrieve an array of an object's own enumerable property names using `Object.keys()`. ```javascript = Object.keys(item1) ``` -------------------------------- ### JavaScript Console Trace Source: https://speedsheet.io/s/javascript?q=console-only Use console.trace() to print the current stack trace to the console. ```javascript console.trace(); ``` -------------------------------- ### Get Set Values Source: https://speedsheet.io/s/javascript Returns an iterable containing all the values in the Set. This can be used to iterate over the Set's elements. ```javascript set1.values(); ``` -------------------------------- ### Handle Click Event Source: https://speedsheet.io/s/javascript?q=event-types-only Attach a listener for 'click' events on the document or specific elements to respond to user clicks. ```javascript document.addEventListener('click', function1); element1.addEventListener('click', function1); ``` -------------------------------- ### Get the Size of a Map Source: https://speedsheet.io/s/javascript Retrieve the number of key-value pairs currently stored in a Map using the `size` property. ```javascript map1.size ``` -------------------------------- ### Define Basic Class Source: https://speedsheet.io/s/javascript?q=class-only Defines a simple JavaScript class with a property, constructor, and methods. ```javascript class Class1 { property1 = value; constructor(param1) { this.property1 = param1; } method1(param1, param2) { return value; } method2(newValue) { // Access: this.property1 = newValue; this.method1(newValue); } } ``` -------------------------------- ### Change Page URL with PushState (Allow Back) Source: https://speedsheet.io/s/javascript?q=history-only Use pushState to change the URL and allow the user to navigate back to the previous state using the back button. ```javascript history.pushState({}, '', '/new_url'); ``` ```javascript history.pushState({state}, '', '/new_url'); ``` -------------------------------- ### Get Random Float Between 0 and 1 Source: https://speedsheet.io/s/javascript?q=colors-only Returns a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive). ```javascript = Math.random() ``` ```javascript let random1 = Math.random(); // Returns 0.38336132177866733 ``` -------------------------------- ### JavaScript Key Cheat Sheet Source: https://speedsheet.io/s/javascript?q=event-types-only A reference for values returned by event.key for various keys, including modifiers, function keys, and navigation keys. ```text // Returned by // = event.key "Alt" "Break" "Control" "Delete" "Down" "Down" "End" "Enter" "Escape" "F1" - "F12" "Home" "Insert" "Left" "Lock" "Lock" "Numlock" "Right" "Shift" "Space" "Tab" "Up" "Up" ``` -------------------------------- ### Get Number of Items in Session Storage Source: https://speedsheet.io/s/javascript Returns the total count of key-value pairs currently stored in session storage. ```javascript = sessionStorage.length ``` -------------------------------- ### Submitting a Form Source: https://speedsheet.io/s/javascript Programmatically submit an HTML form. ```javascript form1.submit(); ``` -------------------------------- ### Get URL Parameter Value Source: https://speedsheet.io/s/javascript Retrieves the value of a specific URL query parameter. Returns null if the parameter does not exist. ```javascript var url = new URL("https://speedsheet.io/s/http?q=data+types"); var search = url.searchParams.get('search'); console.log('search = ', search); ``` ```javascript (new URL(location.href)).searchParams.get(parameter_name); ``` -------------------------------- ### Handle Errors with Try-Catch Source: https://speedsheet.io/s/javascript Wrap `await` calls within a `try...catch` block to handle potential rejections from Promises. ```javascript try { await function1(); } catch (error) { ... } ``` -------------------------------- ### Get Element Attribute Source: https://speedsheet.io/s/javascript?q=Element-Only Retrieve the value of a specified attribute from an element using `getAttribute()`. Returns `null` if the attribute is not found. ```javascript element1.getAttribute('name'); ``` -------------------------------- ### Move Forward in History Source: https://speedsheet.io/s/javascript?q=history-only Use the forward() method to move the browser to the next page in the session history. ```javascript history.forward(); ``` -------------------------------- ### Get Difference in Seconds Source: https://speedsheet.io/s/javascript?q=date-only Calculates the difference between two Date objects in seconds. The result is a number representing the time difference. ```javascript date1 - date2 ``` -------------------------------- ### Get Array Element by Index Source: https://speedsheet.io/s/javascript?q=array-only Accesses an element in an array using its zero-based index. Out-of-bounds indexes return undefined. ```javascript = array1[index] ``` -------------------------------- ### Copy a Map Source: https://speedsheet.io/s/javascript Create a shallow copy of an existing Map by passing it to the Map constructor. ```javascript map2 = new Map(map1) ``` -------------------------------- ### Get the Document Page Title Source: https://speedsheet.io/s/javascript?q=dom-only Retrieve the current title of the HTML document using the `title` property of the `document` object. ```javascript document.title ``` -------------------------------- ### Call Object Method Source: https://speedsheet.io/s/javascript Execute an object's method by appending parentheses `()` to the method name. ```javascript object1.method1(); let user1 = { id: 42, name: "your_name_here", idAndName: function() { return this.id + " " + this.name; } } let idAndName = user1.idAndName(); console.log(idAndName); ``` -------------------------------- ### Access the Document Body Source: https://speedsheet.io/s/javascript?q=dom-only Access the `body` property of the `document` object to get a reference to the `` element of the HTML document. ```javascript document.body ``` -------------------------------- ### JavaScript Associative Array - Get All Keys Source: https://speedsheet.io/s/javascript?q=associative-array-only Provides the JavaScript code to retrieve an array containing all the keys from an associative array. ```javascript = Object.keys(array1); ``` -------------------------------- ### Element - Visibility - Show Source: https://speedsheet.io/s/javascript?q=Element-Only Shows an element by setting its display style. Note that the display value might need adjustment based on the element's type (e.g., 'block', 'inline-block'). ```APIDOC ## Element - Visibility - Show ### Description Shows an element by setting its display style. Note that the display value might need adjustment based on the element's type (e.g., 'block', 'inline-block'). ### Method ```javascript element1.style.display = 'block'; ``` ``` -------------------------------- ### Delete Multiple Items from Array Source: https://speedsheet.io/s/javascript?q=array-only Deletes a specified number of items from an array starting at a given index. Returns the deleted items. ```javascript array1.splice(index, count); ``` -------------------------------- ### Get Element Tag Name Source: https://speedsheet.io/s/javascript Retrieve the tag name of an HTML element in uppercase using `tagName`. `nodeName` is generally preferred. ```javascript element1.tagName; ``` -------------------------------- ### Iterate Over Map Using forEach Source: https://speedsheet.io/s/javascript Use the `forEach()` method to iterate over a Map, providing a callback function that receives the value and key. ```javascript map1.forEach ((value, key) => { ... }) ``` -------------------------------- ### Get the first child element by selector Source: https://speedsheet.io/s/javascript?q=Element-Only Retrieve the first descendant element that matches a specified CSS selector using `querySelector`. ```javascript parentElement.querySelector('selector'); ``` -------------------------------- ### Write Text to Clipboard Source: https://speedsheet.io/s/javascript?q=clipboard-only Copies the provided text string to the system clipboard. Ensure the browser supports the Clipboard API. ```javascript navigator.clipboard.writeText('text'); ``` -------------------------------- ### Get Element by ID Source: https://speedsheet.io/s/javascript?q=Element-Only Retrieves a single HTML element by its unique ID. Returns null if no element with the specified ID is found. ```javascript document.getElementById('id') ``` -------------------------------- ### Creating a New Event Source: https://speedsheet.io/s/javascript Creates a new custom event with a specified name. The event name can be any string. ```javascript new Event('eventName') ``` -------------------------------- ### JavaScript Single-Line Comment Source: https://speedsheet.io/s/javascript Shows the syntax for single-line comments in JavaScript, which start with double forward slashes (//) and extend to the end of the line. ```javascript // This is a comment. ``` -------------------------------- ### Create a New HTML Element Source: https://speedsheet.io/s/javascript?q=Element-Only Use `document.createElement()` to create a new HTML element of a specified tag type. You can then append it to the DOM. ```javascript let paragraph = document.createElement('p'); paragraph.innerHTML = 'This is a new paragraph.'; let body = document.querySelector('body'); body.appendChild(paragraph); ``` -------------------------------- ### Find Substring Index Source: https://speedsheet.io/s/javascript Returns the starting index of the first occurrence of a specified substring within a string. Returns -1 if the substring is not found. ```javascript value.indexOf(search_value) ``` -------------------------------- ### Access Class Method Outside Class Source: https://speedsheet.io/s/javascript Demonstrates accessing a class method from an instance of the class. ```javascript = item1.method1(...); ``` -------------------------------- ### Get Item from Session Storage Source: https://speedsheet.io/s/javascript Retrieves the string value associated with a given key from session storage. Returns null if the key does not exist. ```javascript sessionStorage.setItem("name", "your_name_here"); let name = sessionStorage.getItem("name"); console.log(name); ``` -------------------------------- ### Bind Function to Object Instance Source: https://speedsheet.io/s/javascript Use the `bind()` method to associate a function with a specific object instance. This is useful for callbacks. ```javascript item1.function1.bind(itemToBeBoundTo); ``` -------------------------------- ### Split String into First N Elements Source: https://speedsheet.io/s/javascript Splits a string into an array of substrings using a specified delimiter and returns a specified number of elements from the beginning of the array. ```javascript const original = "one two three"; const first = original.split(" ", 1); // Returns [ "one" ] ``` ```javascript const original = "one two three"; const firstAndSecond = original.split(" ", 2); // Returns [ "one", "two" ] ``` -------------------------------- ### Getting Local Storage Item Source: https://speedsheet.io/s/javascript Retrieves the string value associated with a given key from local storage. Returns null if the key does not exist. ```javascript localStorage.setItem("name", "your_name_here"); let name = localStorage.getItem("name"); console.log(name); ``` -------------------------------- ### Get Element Node Name Source: https://speedsheet.io/s/javascript Retrieve the type of the node as a string using `nodeName`. For HTML elements, this is typically the tag name in uppercase. ```javascript element1.nodeName; ``` -------------------------------- ### Send POST Request with Fetch Source: https://speedsheet.io/s/javascript Sends a POST request with specified data and headers using the Fetch API. Supports async/await or Promises. ```javascript response = await fetch(url, { method: 'POST', body: data, headers: ...}); ``` ```javascript fetch(url,{ method: 'POST', body: data, headers: ...}) .then(response => {...}); ``` ```javascript var url = 'https://httpbin.org/post'; var data = {name: 'Arthur Dent'}; var response = await fetch(url, { method: 'POST', body: JSON.stringify(data), headers: new Headers({'content-type': 'application/json'})}); console.log(response); ```