SNHPS
Quick and easy code snippets
add-event-to-multiple-elements.js

Add an event listener to every element that matches the given selector.

document.querySelectorAll('.snippet-wrapper .snippet-description').forEach(function(event_element)
{
	event_element.addEventListener('click', function(event)
	{
		alert('Element clicked!');
	});
});
add-items-to-array-at-position.js

Clone the given array and add one or more items to the specified position.

function add_items_to_array_at_position(array, index, new_items)
{
    return [...array.slice(0, index), ...new_items, ...array.slice(index)];
}

let old_array = [1,2,5];

let new_array = add_items_to_array_at_position(old_array, 2, [3,4]);

console.log(new_array);

//Output: [1,2,3,4,5]
delegate-event.js

Delegate an event using a parent element and child selector.

function delegate_event(event_type, ancestor_element, target_element_selector, listener_function, args)
{	
	ancestor_element.addEventListener(event_type, function(event)
	{
		let is_direct_match = event.target.matches(target_element_selector);
		let closest_ancestor_match = event.target.closest(target_element_selector);
		
		if (is_direct_match)
		{
			(listener_function)(event, event.target, args);
		}
		
		else if (closest_ancestor_match !== null && ancestor_element.contains(closest_ancestor_match))
		{
			(listener_function)(event, closest_ancestor_match, args);
		}
	});
}

function your_function_here(event, element, args)
{
	alert('foobar!');
}

delegate_event('click', document, '.alert-button', your_function_here, {'foo': 3, 'bar': 'yes'});
document-ready.js

Wait for the document to be ready.

document.addEventListener('DOMContentLoaded', function()
{
	alert('The DOM is now ready to be manipulated!');
});
escape-html.js

Sanitize a string that will be inserted into an HTML document.

function escape_html(string)
{
    return ((string === null) ? null : string.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#039;'));
}
fetch.js

Send a POST request using the new Fetch API.

let form_data = new FormData();
form_data.append('action', 'my_wordpress_ajax_function');
form_data.append('foo', 'bar');

fetch('https://example.com/my_ajax_url', {method: 'POST', headers: {}, body: form_data})
.then
(
	response => response.json()
)
.then
(
	data =>
	{
		console.log(data);
		
		if (data.status === 'success')
		{
			alert('Success!');
		}
		
		else if (data.status === 'error')
		{
			alert('Error...');
		}
		
		else
		{
			throw 'Unexpected response status';
		}
	}
)
.catch(error =>
{
	console.log(error);
	alert('An unknown error occurred. Please try again later or contact us for assistance.');
});
format-numbers.js

Convert a number to a string with the specified number of decimal places and an optional comma.

function format_number(number, num_decimals, include_comma)
{
    return number.toLocaleString('en-US', {useGrouping: include_comma, minimumFractionDigits: num_decimals, maximumFractionDigits: num_decimals});
}

format_number(1234.56789, 2, true); // Returns '1,234.57'
format_number(9001.42, 0, false); // Returns '9001'
get-base64-filesize.js

Calculate the expected filesize of the given base64 string.

function get_base64_filesize(base64)
{
	let content_without_mime = base64.split(",")[1];
	let size_in_bytes = window.atob(content_without_mime).length;
	return size_in_bytes;
}
get-substring.js

Get the text between two substrings, inclusive or exclusive, and optionally trim it afterwards.

function get_substring(full_string, substring_1, substring_2, inclusive, trim)
{
    if (full_string === null) { return null; };

    let substring_1_start = full_string.indexOf(substring_1);
    let substring_2_start = full_string.indexOf(substring_2);
    
    if (substring_1_start === -1 || substring_2_start === -1) { return null; }
    
    let substring_1_end = substring_1_start + substring_1.length;
    let substring_2_end = substring_2_start + substring_2.length;
    
    let return_string = inclusive ? (full_string.substring(substring_1_start, substring_2_end)) : (full_string.substring(substring_1_end, substring_2_start));

    return trim ? return_string.trim() : return_string;
}

//Returns 'and ice'
get_substring('I like cake and ice cream', 'cake', 'cream', false, true);
konami-code.js

Trigger a customizable easter egg when a user inputs the Konami Code with their keyboard arrows or phone swipes.

let Secret=function(t){var e={addEvent:function(t,e,n,o){t.addEventListener?t.addEventListener(e,n,!1):t.attachEvent&&(t["e"+e+n]=n,t[e+n]=function(){t["e"+e+n](window.event,o)},t.attachEvent("on"+e,t[e+n]))},removeEvent:
function(t,e,n){t.removeEventListener?t.removeEventListener(e,n):t.attachEvent&&t.detachEvent(e)},input:"",pattern:"38384040373937396665",keydownHandler:function(t,n){if(n&&(e=n),e.input+=t?t.keyCode:event.keyCode,e.input.length>e.pattern.length
&&(e.input=e.input.substr(e.input.length-e.pattern.length)),e.input===e.pattern)return e.code(e._currentLink),e.input="",t.preventDefault(),!1},load:function(t){this._currentLink=t,this.addEvent(document,"keydown",this.keydownHandler,this),this.iphone.load(t)},unload:
function(){this.removeEvent(document,"keydown",this.keydownHandler),this.iphone.unload()},code:
function(t){window.location=t},iphone:{start_x:0,start_y:0,stop_x:0,stop_y:0,tap:!1,capture:!1,orig_keys:"",keys:["UP","UP","DOWN","DOWN","LEFT","RIGHT","LEFT","RIGHT","TAP","TAP"],input:[],code:function(t){e.code(t)},touchmoveHandler:
function(t){if(1===t.touches.length&&!0===e.iphone.capture){var n=t.touches[0];e.iphone.stop_x=n.pageX,e.iphone.stop_y=n.pageY,e.iphone.tap=!1,e.iphone.capture=!1,e.iphone.check_direction()}},touchendHandler:
function(){if(e.iphone.input.push(e.iphone.check_direction()),e.iphone.input.length>e.iphone.keys.length&&e.iphone.input.shift(),e.iphone.input.length===e.iphone.keys.length)
{for(var t=!0,n=0;n<e.iphone.keys.length;n++)e.iphone.input[n]!==e.iphone.keys[n]&&(t=!1);t&&e.iphone.code(e._currentLink)}},touchstartHandler:
function(t){e.iphone.start_x=t.changedTouches[0].pageX,e.iphone.start_y=t.changedTouches[0].pageY,e.iphone.tap=!0,e.iphone.capture=!0},load:function(t){this.orig_keys=this.keys,e.addEvent(document,"touchmove",this.touchmoveHandler),
e.addEvent(document,"touchend",this.touchendHandler,!1),e.addEvent(document,"touchstart",this.touchstartHandler)},unload:
function(){e.removeEvent(document,"touchmove",this.touchmoveHandler),e.removeEvent(document,"touchend",this.touchendHandler),e.removeEvent(document,"touchstart",this.touchstartHandler)},check_direction:
function(){return x_magnitude=Math.abs(this.start_x-this.stop_x),y_magnitude=Math.abs(this.start_y-this.stop_y),x=this.start_x-this.stop_x<0?"RIGHT":"LEFT",
y=this.start_y-this.stop_y<0?"DOWN":"UP",result=x_magnitude>y_magnitude?x:y,result=!0===this.tap?"TAP":result,result}}};return"string"==typeof t&&e.load(t),"function"==typeof t&&(e.code=t,e.load()),e};"undefined"!=typeof module
&&void 0!==module.exports?module.exports=Secret:"function"==typeof define&&define.amd?define([],function(){return Secret}):window.Secret=Secret;
new Secret(function()
{
	alert('Konami code triggered');
});
trim-and-remove-blank-lines.js

Trim each line in the given string, then remove any blank lines.

function trim_and_remove_blank_lines(string)
{
    return string.replace(/^(?=\n)$|^\s*|\s*$|\n\n+/gm, "")
}

//Returns 'Line 1\nLine2\nLine4'
trim_and_remove_blank_lines("Line 1 \nLine2\r\n\r\nLine4\n")

This website is owned and operated by SiteBolts. All the code snippets found here are intended to be a starting point and should not be treated as a perfect solution to every problem. We do not guarantee the performance, reliability, or security of the code found on this website. As always, you should ensure that you have adequate backups before adding, changing, or executing any code.