Use
Hide elements
Purpose : Hides all elements that match the given selector or the specified DOM element by setting their display style to none
Parameters
- selectorOrElement: CSS selector string or DOM element.
import { u_hide } from '@andresclua/jsutil';
// Hide all elements with the class 'hide-me'
u_hide('.hide-me');
u_hide(document.querySelectorAll('.hide-me'));
u_hide(document.querySelector('.hide-me'));
u_hide(document.getElementById('hide-me'));
As you can see, the first argument is a selector, designed to streamline the process of selecting elements in JavaScript. This approach treats both single elements and collections of elements uniformly. By always returning an array (or an array-like object), it enables consistent iteration and manipulation patterns in the code that follows. Simple as that!
Show elements
Purpose: Shows all elements that match the given selector or the specified DOM element by setting their display style to block.
Parameters
- selectorOrElement: CSS selector string or DOM element.
import { u_show } from '@andresclua/jsutil';
// Show all elements with the class 'show-me'
u_show('.show-me');
u_show(document.querySelectorAll('.show-me'));
u_show(document.querySelector('.show-me'));
u_show(document.getElementById('show-me'));
Style elements
Purpose: Applies a set of CSS styles to elements that match the given selector.
Parameters
- selector: CSS selector string
- styles: Array of objects representing CSS properties and values.
import { u_style } from '@andresclua/jsutil';
// Apply multiple styles to elements with class 'styled-elements'
u_style('.styled-elements', [{ color: 'red' }, { fontSize: 16 }]); // if no unit is define will use pixels
u_style('.styled-elements', [{ background: 'red' }, { display: 'block' }]);
u_style(document.querySelector('.styled-elements'), [{ background: 'red' }, { display: 'block' }]);
Add Class
Purpose: Adds one or more class names to all elements that match the given selector or the specified DOM element.
Parameters
- selector: CSS selector string
- classNames: A string containing one or more class names separated by spaces.
import { u_addClass } from '@andresclua/jsutil';
// Add 'class1' and 'class2' to elements with class 'add-classes-to-me'
u_addClass('.add-classes-to-me', 'class1 class2');
Remove Class
Purpose: Removes one or more class names from all elements that match the given selector or the specified DOM element.
Parameters
- selector: CSS selector string or DOM element.
- classNames: A string containing one or more class names separated by spaces.
import { u_removeClass } from '@andresclua/jsutil';
// Remove 'class1' and 'class2' from elements with class 'remove-classes-from-me'
u_removeClass('.remove-classes-from-me', 'class1 class2');
Toggle Class
Purpose: Toggles one or more class names for all elements that match the given selector or the specified DOM element. If the class exists on the element, it is removed; if it does not exist, it is added.
Parameters
- selector: CSS selector string or DOM element.
- classNames: A string containing one or more class names separated by spaces.
import { u_toggleClass } from '@andresclua/jsutil';
// Toggle 'class1' and 'class2' on elements with class 'toggle-classes-on-me'
u_toggleClass('.toggle-classes-on-me', 'class1 class2');
Matches
Purpose: Provides a versatile way to query the DOM and check for the presence of elements that meet specific criteria. It enhances the flexibility of element selection by allowing checks not just based on class names, but on any attribute. When dealing with classes, the function is capable of handling both single class names and combinations, offering a robust solution for more complex matching scenarios.
Parameters
-
selector: A CSS selector string or a DOM element. This parameter specifies the set of elements to be checked against the matching criteria.
-
classNames: A string or an array of strings that the elements are matched against. The nature of this identifier changes based on the attribute parameter. For the class attribute, it can be a single class name or multiple class names (as a space-separated string or an array). For other attributes, it is typically a single string value.
-
attribute: (optional): A string specifying the attribute to match against. The default value is ‘class’, targeting element classes. However, it can be any valid attribute present on an element, such as ‘id’, ‘data-*’ attributes, etc.
import { u_matches } from '@andresclua/jsutil';
// Check if there's an element with the class 'active'
const hasActive = u_matches('.menu-item', 'active');
import { u_matches } from '@andresclua/jsutil';
// Check if there's an element containing both 'active' and 'highlighted' classes
const hasActiveAndHighlighted = u_matches('.menu-item', 'active highlighted');
import { u_matches } from '@andresclua/jsutil';
// Check if there's an element with a data-attribute 'data-role' equal to 'admin'
const hasAdminRole = u_matches('div', 'admin', 'data-role');
Get Attribute
Purpose: Retrieves the value of a specified attribute from the first element that matches the given selector or from the specified DOM element.
Parameters
- selector: CSS selector string or DOM element.
- attrName: The name of the attribute whose value is to be retrieved.
import { u_getAttr } from '@andresclua/jsutil';
console.log(u_getAttr('.js--u_get', 'data-name'));
Returns String | null: The value of the specified attribute from the first matched element. Returns null if no element is found or if the element does not have the specified attribute.
Set Attribute
Purpose: Sets a specified attribute to a given value for all elements that match the given selector or for the specified DOM element.
Parameters
- selector: A CSS selector string or a DOM element. This parameter targets the element(s) to which the attribute value will be set.
- attrName: The name of the attribute to be set.
- attrValue: The value to assign to the specified attribute.
import { u_setAttr } from '@andresclua/jsutil';
// Set the 'target' attribute to '_blank' for all links
u_setAttr('a', 'target', '_blank');
String To Boolean
Purpose: Converts a string input to its boolean equivalent.
Parameters
- input: The string input to be converted. Accepts “true”, “false”, “1”, or “0” (case-insensitive).
Returns
- Boolean: Returns true for inputs “true” or “1”, and false for inputs “false” or “0”.
Throws
- Error: If the input is not one of the accepted values (“true”, “false”, “1”, or “0”), the function throws an error indicating invalid input.
import { u_stringToBoolean } from '@andresclua/jsutil';
const boolValue = u_stringToBoolean("True"); // returns true
const anotherBoolValue = u_stringToBoolean("0"); // returns false
String To Number
Purpose: Converts a string input to its boolean equivalent.
Parameters
- string: The string input to be converted to a number. Should represent a valid numerical value.
Returns
- Number: The numerical representation of the input string.
Throws
- Error: If the input string cannot be converted to a number, the function throws an error indicating the input is invalid.
import { stringToNumber } from '@andresclua/jsutil';
const numValue = u_stringToNumber("123.45"); // returns 123.45
const anotherNumValue = u_stringToNumber("abc"); // throws Error
Browser Type
Purpose: Identifies if the current user’s browser matches the specified browser.
Parameters
- browser: A string indicating the browser to check for. Supported values are ‘chrome’, ‘safari’, ‘firefox’, ‘ie’ (Internet Explorer), and ‘edge’.
Returns
- Boolean | null: Returns true if the current browser matches the specified browser, false if it does not match, and null if the browser is not recognized or the input does not match any supported browser.
import { u_browser } from '@andresclua/jsutil';
const isChrome = u_browser('chrome'); // returns true if Chrome, false if not, null if unrecognized
Feature detection is where you don’t try to figure out which browser is rendering your page, but instead, you check to see if the specific feature you need is available. If it’s not, you use a fallback. In those rare cases where behavior differs between browsers, instead of checking the user agent string, you should instead implement a test to detect how the browser implements the API and determine how to use it from that.
System
Purpose: Determines if the current user’s system matches the specified system or capability.
Parameters
- system: A string specifying the system or capability to check for. Supported values are ‘touch’ (for touch capability), ‘android’, ‘ios’, ‘windows’ and ‘mac’.
Returns
- Boolean | null: Returns true if the current system matches the specified system or has the specified capability, false otherwise.
import { u_system } from '@andresclua/jsutil';
u_system('ios') // returns true if Ios Device, false if not, null if unrecognized
Take Your Time
Purpose: This function is an asynchronous utility designed to introduce a delay or pause in the execution of JavaScript code. It leverages the Promise object and setTimeout to wait for a specified amount of time before proceeding. This function is particularly useful for simulating delays, such as waiting for an asynchronous operation to complete, or for introducing pauses in animations or other time-dependent logic.
Parameters
- time: (optional) The amount of time to wait before resolving the promise, in milliseconds. The default value is 100 milliseconds. This parameter must be a number.
Returns
- Promise: A promise that resolves after the specified time delay. If time is not a valid number, the promise is rejected with an error. id.
import { u_take_your_time } from '@andresclua/jsutil';
(async () => {
console.log('Wait starts');
const result = await u_take_your_time(1200);
console.log('Wait ends');
})()
// or
u_take_your_time(1200).then(() => {
console.log('after 1200 ms')
});