Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@htmlguyllc/jpack

Package Overview
Dependencies
Maintainers
1
Versions
191
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@htmlguyllc/jpack

Core Javascript Library of Everyday Objects, Events, and Utilities

  • 9.0.15
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
19
increased by533.33%
Maintainers
1
Weekly downloads
 
Created
Source

Build Status

BuildStatus

jPack

jPack is a vanilla javascript library of components, classes, plugin wrappers, and utilities designed to make building custom websites and web applications simpler.

But why?

Many plugins and libraries are too generic, verbose, bulky, lacking, or have a lot of dependencies. Much of what is included here is stuff that I've written several times, in several different ways, using jQuery in the past (or wrapping other jQuery plugins). The goal of this library is to allow me (and you, now that it's open source) to integrate slim, mostly dependency-free, components as-needed with more specific use-cases than what is currently offered elsewhere.

...where else can you get a component to grab a form from another page and stick it on the current one with XHR and XHR submission in 4 lines of custom JS?

What's Included

ComponentDemoData TypeWhat it does
navigationobjectGrabs HTML from a URL and replaces content on the current page. Handles browser history, meta title swaps, and offers several callbacks
XHRFormclassAdds an on-submit listener and sends the form values using XHR with callbacks for success/failure
FormFromURL (extends XHRForm)classGrabs a form from a URL and places it on the current page (examples/FormModalFromURL shows how to put the form in a modal) and then uses an XHR request to submit the form
requestdemoobjectProvides a wrapper for window.location and easy querystring interaction
SitedemoclassA generic website class with properties for id, name, and config - useful for multi-tenant applications where you need to know which site is being viewed
UserdemoclassA generic user class with properties for id, name, email, phone, etc - also allows for front-end permission checks
stringsdemoobjectContains methods for semi-common string manipulation like creating a getter from a string ('hi' = 'getHi')
type_checksdemoobjectValidate the value of a variable with higher specificity than built-in functions. For instance, you can validate an object contains specific keys and throw errors if not, or if it contains keys that you didn't define
domdemoobjectHas methods for converting just about anything into a native DOM Element or array of them (you can provide a string selector, jQuery object, native DOM object, etc). Also has some shortcuts for common DOM checks/manipulation (like removing an element, verifying an element exists in the DOM, or replacing an element with HTML)
eventsdemoobjectIncludes methods for attaching event handlers including shorthand methods which create handlers that prevent the browser's default action (onclick, onsubmit)
ToggleOnMobiledemoclassToggle an element's visibility when you click a button. By default, the element is visible, but if the button is visible, the element will be hidden until the button is clicked. If the element is visible and the user clicks outside of it, the element is hidden. If the window is resized, the element will be shown or hidden based on visibility of the button.

Installation

Standard Global

Download the latest release, unzip and move it into your website's public folder, then include it in your HTML.

Use either jpack.min.js or jpack.bundled.min.js, BUT NOT BOTH. The bundled file includes the dependencies and you don't need them if you already have them in your project.

<script href="/@htmlguyllc/jpack/dist/jpack.bundled.min.js">
<!-- <script href="/@htmlguyllc/jpack/dist/jpack.min.js"> -->

<script>
//wait for the page to finish loading so we know jpack is ready
window.addEventListener('load', function() {
    
    //now you can take advantage of the jpack library
    jpack.strings.ucfirst('bob'); //Bob
    
    //if you want to change the namespace
    jpack.setGlobal("$");
    
    $.strings.ucfirst('bob');
    
    //if you want to make all global without a namespace - do so at your own risk! Things may conflict!
    jpack.setGlobal();
    
    strings.ucfirst('bob');
};
</script>
With NPM or Yarn:
npm i @htmlguyllc/jpack;
//or
yarn add @htmlguyllc/jpack;
ES6 (Babel)
//a single component from it's own file
import {strings} from '@htmlguyllc/jpack/es/strings';
strings.ucfirst('bob');

//or multiple components from jpack
import {strings, dom} from '@htmlguyllc/jpack';
strings.ucfirst('bob');
dom.exists('a.my-link');

//or a namespaced object containing all components
import * as j from '@htmlguyllc/jpack';
j.strings.ucfirst('bob');
CommonJS (Browserify)
var jpack = require('@htmlguyllc/jpack');

//now use it
jpack.strings.ucfirst('bob');

Dependencies

NameRequired byLink
url-search-params-polyfillrequesthttps://www.npmjs.com/package/url-search-params-polyfill
axiosnavigationhttps://www.npmjs.com/package/axios
formdata-polyfillXHRForm (and anything that extends it)https://www.npmjs.com/package/formdata-polyfill

Documentation


Navigation

[back to top](#whatsincluded)

Grabs HTML from a URL and replaces content on the current page. Handles browser history, meta and page title swaps, and offers several callbacks

PropertiesDefaultNotes
pushStatetrueenables pushing the new URL to the browser's history each time .load() is called
loaderEnabledtrueenables a loader if the the .load() request takes too long
trackHistoryfalsestores the URL and route in an array each time .load() is called to track history
Primary MethodsParams (name:type)ReturnNotes
setConfigconfig:objectselfsets multiple configuration options at once (see examples below for more info)
initHistoryHandlersselfsets event listeners to handle back/forward navigation in the user's browser (only use if pushState is true)
setIncomingElementel:stringselfa selector string for the element being retrieved from another page which contains the HTML you want put on the current page
setReplaceElementel:stringselfa selector string for the element on the current page you want the new HTML to replace
loadurl:string, data:object, callback:function/null, incoming_el:string/null, replace_el:string/null, push_state:boolvoidpulls content from the provided URL and puts it on the current page - also swaps out the page title, metas, and much more
showLoaderselfshows the loader after the delay
hideLoaderselfclears the loader timeout and hides it
reloadcallback:functionselfreloads the current page using .load()
fullReloadvoidperforms a full browser refresh of the current page
redirecturl:stringvoidredirects the user to a new page (no XHR request)
showLoaderselfsets a timeout (using the loaderDelay) with a callback to show the loader
hideLoaderselfcancels the timeout if it hasn't shown yet and hides the loader
resetConfigselfresets config options back to their defaults
Event MethodsParams (name:type)ReturnCallback Params (name:type)Notes
onloadcallback:functionselfel:Element, data:object, config:{ selector:string, replaced_selector:string, route:string/null}add an onload callback
removeOnloadcallback:functionselfremoves an onload callback
onUnloadcallback:functionselfel:Element, data:object, {selector:string, route:string/null}add an unload callback
removeOnunloadcallback:functionselfremoves an unload callback
onFailcallback:functionselferror:string, url:string, data:object, axios_error:object/nulladd a callback when the load() request fails - receives 2 params (error:string, axios_error:object)
removeOnFailcallback:functionselfremoves a failure callback
Setters/GettersParams (name:type)ReturnNotes
getConfigobjectreturns the config options as an object
getIncomingElementstring
getReplaceElementstring
setDatadata:objectselfsets a data object that is automatically passed to every .onload(), .onUnload(), and .onFail() callback
getDataobject
setDataItemkey:string, val:mixedselfsets a single data value
getDataItemkey:stringselfreturns null if it doesn't exist
clearDataselfclears all data
setLoaderDelaydelay:intselfset how long a request should take in ms before the loader displays
getLoaderDelayself
getHistoryarrayreturns an array of objects containing "url" and "route" starting with the first URL passed to .load() and ending with the latest
getLastHistoryRecordobjectreturns an object containing "url" and "route" for the last page grabbed by .load()
To use:
import {navigation} from '@htmlguyllc/jpack/es/navigation';

/**
* Shown with defaults, you don't need to provide all of these, just what you want to modify
* If the defaults are fine, you don't need to call setConfig()
*/
navigation.setConfig({
     trackHistory:false, //keep track of URLs loaded in an array (see setters/getters above for how to retrieve records)
     pushState:true, //push new URLs to the browser's history
     loaderEnabled:true, //show a loader during the request process
     loaderDelay:300, //how long the request needs to take before the loader is shown
     incomingElementSelector:'body', //what element in the content from the URL should be grabbed
     replaceElementSelector:'body', //what element on the page should be replaced with the incoming one
     loaderClasses:'progress page-navigation-loader', //the loader consists of two divs (outer/inner) and uses Bootstrap 4's progress-bar classes (no styling is included so you should either add Bootstrap, change these classes and add your own styling, or just disable the loader)
     loaderInnerDivClasses:'progress-bar progress-bar-striped progress-bar-animated',
});

//attaches event handlers to automatically use XHR to reload pages when the user pushes the back and forward buttons in their browser (will not work if pushState is false)
navigation.initHistoryHandlers();

/**
* Add as many onload callbacks as you'd like to run every time a page is loaded
* 
* el is the new element on the page
* data the data object you set when you call .load() or using setData/setDataItem (see above method details)
* config is an object {selector, replaced_selector, route}
*    selector is the "incomingSelector" used to grab the new element
*    replacedSelector is the selector used to find the element that was replaced
*    route is the new page's route (if set in JSON or HTML response)
*/
navigation.onload(function(el, data, config){
    
    //some things you might want to run every time a page loads:
   
   //if gtag is set (google analytics), push a page view
   if( typeof gtag !== 'undefined' ) {
       gtag('config', 'GA_MEASUREMENT_ID', {
           page_path: request.getURIWithQueryString()
       });
   }
   
   //if trackHistory is true, you can grab the last history record (or all - see getters/setters above)
   var last_history = navigation.getLastHistoryRecord();
   if( last_history ){
       const last_url = last_history.url;
       const last_route = last_history.route;
   }
   
   //scroll to the top of the page
   window.scrollTo(0, 0);
   
   //.. do more...like init tooltip plugins
});

/**
* Add as many unload callbacks as you'd like to run every time a page is loaded (just before the new HTML is replaced with the old)
* 
* Params are the same as onload except config doesn't have replacedSelector
* 
* Keep in mind this is the element that will be removed shortly (and config.selector is the selector used to retrieve that element) 
* 
*/
navigation.onUnload(function(el, data, config){
   //.. do something...like remove event handlers or destroy plugins 
});

/**
* Adds as many failure callbacks you'd like to run every time a page fails to load
* 
* error is the string message
* url is the requested URL that failed
* data is the data you provided to be passed onto that page
* axios_error is an error object set by axios that will be available if that's where the error occurred
*/
navigation.onFail(function(error, url, data, axios_error){
    //.. do something...like show an error popup for the user or log the issue
});

/**
* Now load pages!
* 
* It might look strange to you that you're passing values that are already in-scope for your callback. 
*    This is done for 2 reasons. 
*       1) It protects the data you passed from modification (your object is cloned inside .load())
*       2) It passes that object to all the global onload() callbacks as well
*/
let data = {pass_this:'hi!'};
navigation.load('/my-url', data, function(el, data, config){ 
    const passed = data.pass_this; //passed = 'hi!'
});

/**
* One of the easiest ways to use this plugin is to tie an event handler to onClick of any link containing a class or attribute
* In this example, all you have to do is add data-href in your link (like this: <a href="my-url" data-href>Link</a>)
*/
import {events} from '@htmlguyllc/jpack/es/events';

events.onClick('[data-href]', function(){
   navigation.load(this.href);
});

/**
* Want to pass a value to all onload callbacks? It's easy!
*/
navigation.setData({
    scrollToTop: true
});
//or
navigation.setDataItem('scrollToTop', true);

/**
* Now load a page and use it!
*/
navigation.load('/my-url', {}, function(el, data){
    if( data.scrollToTop ){
        window.scrollTo(0,0);
    }
});

/**
* You can override global data per-request when you provide it to the .load() method
*/
navigation.load('/my-url', {
    scrollToTop: false
}, function(el, data){
    if( data.scrollToTop ){
        //won't be called
        window.scrollTo(0,0);
    }
});


XHRForm

[back to top](#whatsincluded)

Adds an on-submit listener and sends the form values using XHR with callbacks for success/failure. Automatically prevents the user from submitting the form several times at once. It must finish processing before it can be submitted again.

Method/PropertyParams (name:type)ReturnNotes
constructorform:Element,options:objectself
setXHRSubmitenabled:boolselfenable/disable the XHR submission of the form
setSubmitMethodmethod:stringselfoverride the form and provide a method (GET, POST, PATCH)
getSubmitMethodmethod:string
setSubmitURLurl:mixedselfpass null to use the form's action, function to dynamically generate the URL (receives the form as a param), or string
getSubmitURLurl:stringreturns whatever was set in the constructor or using setSubmitURL, not the final URL
getFinalSubmitURLform:Elementurl:stringreturns the URL the form will be submitted to after running the function (if it is one) and using all fallbacks
attachSubmitHandlerform:mixedselfattaches the event listener to on submit of the passed form
onSuccesscallback:functionselfadds an onSuccess callback (you can add as many as you'd like)
clearOnSuccessCallbacksself
triggerOnSuccessresponse:mixed, form:Elementselfruns all onSuccess callbacks and passes the server's response and the form element
onErrorcallback:functionselfadds an onError callback (you can add as many as you'd like)
clearOnErrorCallbacksself
triggerOnErrorerror:string, response:mixed, form:Elementselftriggers all onError callbacks and passes the error string, server response, and form Element
submitFormform:Elementselfgets URL and method, checks form validity using .validate(), gets values, submits, and kicks off callbacks
getFormValuesform:Elementselfreturns data from the form to be submitted - override this if you want to manipulate it first
setValidateCallbackcallback:functionis_valid:boolpass a function to validate the form and return true if it's valid, false if it's not. False prevents form submission so you must display errors for the user within here. The default callback uses Bootstrap 4's "was-validated" class to show errors and HTML5's :invalid attribute to validate
validateform:Elementboolpasses the form to the validate callback and returns the response
To use:
import {XHRForm} from '@htmlguyllc/jpack/es/forms'; 

//shown with defaults
var remote_form = new XHRForm('form[name="my_form"]', {
        xhrSubmit: true, //wouldn't make a whole lotta sent to use this if this were false lol, but it's here for extending classes and incase you want to toggle it for whatever reason
        submitURL:null, //when null, the form's action will be used (if explicitly defined), otherwise it falls back to the URL the form was retrieved from
        submitMethod:null, //when null, the form's method will be used (if explicitly defined), otherwise it falls back to POST
        onError: function(error, response, form){ alert(error); }, //although you can add more, you can only pass 1 to start with in the constructor
        onSuccess: function(response, form){ //although you can add more, you can only pass 1 to start with in the constructor 
            if(typeof response.success === "string"){ alert(response.success); }
            else{ alert("Your submission has been received"); }
        },
        //validate the form, display any errors and return false to block submission
        validateForm: function(form){
            //add .was-validated for bootstrap to show errors
            form.classList.add('was-validated');
    
            //if there are any :invalid elements, the form is not valid
            const is_valid = !form.querySelector(':invalid');
    
            //if it's valid, clear the validation indicators
            if( is_valid ) form.classList.remove('was-validated');
    
            return is_valid;
        }
});

//attach the submission handler
remote_form.attachSubmitHandler();

FormFromURL

FormFromURL extends [XHRForm](#xhrform)

[back to top](#whatsincluded)

Grabs a form from a URL and places it on the current page (examples/FormModalFromURL shows how to put the form in a modal) and then uses an XHR request to submit the form

Method/PropertyParams (name:type)ReturnNotes
constructorurl:string, options:objectself
setURLurl:stringselfset the URL to pull the form from
getURLurl:string
setIncomingElementSelectorselector:stringselfset a selector for the form element or it's parent that is returned by the URL
getIncomingElementSelectorselector:string
setInsertIntoElementelement:mixedselfset the element that the form should be inserted into
getInsertIntoElementelement:mixed
getFormvoidpulls the form from the URL and runs the insertForm method
insertFormparsed_content:object, response:mixed, form:Element/nullel:Elementinserts the form into the parent element, attaches the submit handler, triggers onload, and returns the parent element
onloadcallback:functionselfadds a callback function to be run when the form is loaded on the page
clearOnloadCallbacksselfremoves all onload callbacks
triggerOnloadform:Elementselfruns all onload callbacks and passes the form to them

There are several methods and properties inherited from XHRForm that are not listed here. See XHRForm above for those details

To use:
import {FormFromURL} from '@htmlguyllc/jpack/es/forms'; 

//shown with defaults
var remote_form = new FormFromURL('/my-form', {
        incomingElementSelector: null, //when null, it assumes the entire response is the form's HTML
        insertIntoElement: null, //error on null, must provide this
        onload: function(form){ return this; }, //although you can add more, you can only pass 1 to start with in the constructor
        xhrSubmit: true, 
        submitURL:null, //when null, the form's action will be used (if explicitly defined), otherwise it falls back to the URL the form was retrieved from
        submitMethod:null, //when null, the form's method will be used (if explicitly defined), otherwise it falls back to POST        
        onError: function(error, response, form){ alert(error); }, //although you can add more, you can only pass 1 to start with in the constructor
        onSuccess: function(response, form){ //although you can add more, you can only pass 1 to start with in the constructor 
            if(typeof response.success === "string"){ alert(response.success); }
            else{ alert("Your submission has been received"); }
        }, 
        //validate the form, display any errors and return false to block submission
        validateForm: function(form){
            //add .was-validated for bootstrap to show errors
            form.classList.add('was-validated');
    
            //if there are any :invalid elements, the form is not valid
            const is_valid = !form.querySelector(':invalid');
    
            //if it's valid, clear the validation indicators
            if( is_valid ) form.classList.remove('was-validated');
    
            return is_valid;
        }
});

//grab the form and insert in into the "insertIntoElement"
remote_form.getForm();
How to get and submit a form in 4 lines of javascript:
- Success/failure messages will be shown in an alert - HTML5/browser validation is done on the required field prior to submit

Your javascript

import {FormFromURL} from '@htmlguyllc/jpack/es/forms'; 
new FormFromURL('/email-form', {
    insertIntoElement: 'body.form-container',
}).getForm();

Your HTML

<div class="form-container"></div>

Server response when retrieving /email-form (or, just the HTML without the JSON wrapper)

{
 "html": "<form><input name='email' required='required'><input type='submit' value='Submit'></form>"
}

Server response when submitting to /email-form (success)

{ "success": "Thank you for submitting, your email has been provided to spammers everywhere" }

Server response when submitting to /email-form (error)

{ "error": "Your email is required/Your email is invalid" }
Extending:

FormFromURL extends XHRForm and either can be extended as you need.

See examples/FormModalFromURL for an example


Request

[demo](https://jsfiddle.net/HTMLGuyLLC/73b2kotL/) | [back to top](#whatsincluded)

Provides a wrapper for window.location and easy querystring interaction

Method/PropertyParams (name:type)ReturnNotes
queryn/aURLSearchParamssee https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams#Methods
isHttpsbool
getDomainstring
getDomainWithProtocolstring
getURIstringalso known as the path - does not include querystring
getURIWithQueryStringstringfull URL after the domain
getFullURLstring
appendSlashstring:stringstringadds a slash (if there isn't already one) to the end of a string.
To use:
import {request} from '@htmlguyllc/jpack/es/request'; 

//get product_id from the querystring
var product_id = request.query.get('product_id');

var current_full_url = request.getFullURL();

var full_blog_url = request.appendSlash(request.getDomainWithProtocol())+'blog'; //https://my-domain.com/blog

Site

[demo](https://jsfiddle.net/HTMLGuyLLC/L6brcvo3/) | [back to top](#whatsincluded)

A generic website class with properties for id, name, and config - useful for multi-tenant applications where you need to know which site is being viewed

Method/PropertyParams (name:type)ReturnNotes
getIdstring/int
setIdid:string/intthis
getNamestringthis
setNamename:stringthis
getConfigobjectthis
setConfigconfig:objectthisoverwrites all config
getConfigItemmixedreturns an individual item from config
setConfigItemkey:string,val:mixedthissets the value of an individual item in config
populatedata:objectthissets provided values all at once (id,name,config)
Instantiation with current site data:

The easy way:

Create an object named $site with values from your server (prior to including jpack)

<?php
    $user = []; //get user from database/API
?>
<script>
const $user = {
    id: <?php echo $user['id']; ?>,
    fname: "<?php echo $user['fname']; ?>",
    //..
    permissions: JSON.parse("<?php echo json_encode($user['permissions']); ?>"),
    additionalData: JSON.parse("<?php echo json_encode([
        'user_type'=>$user['user_type'],
        //whatever else you might want to pass
    ]); ?>"),
    //..
};
</script>

Then instantiate the Site class in your JS file somewhere

const cur_site = new Site($site);
cur_site.getId();

@see: /examples/CurrentSiteSingleton for a method of instantiating the current site once and using everywhere Note: Even though that creates a singleton which is available anywhere, it's still highly recommended that you pass that object to functions and methods where it is used (dependency injection)

The harder way:

Perform an XHR request to grab site details via a JSON API, then run the populate method on the site object.

import {Site} from '@htmlguyllc/jpack/es/site';
 
//this example uses jQuery's shorthand AJAX call, you can use axios or any request you want
$.get('/my-site-info-endpoint.php', function(data){
    //don't forget error handling!
    const cur_site = new Site(JSON.parse(data));
});

Of course you can use this class for any site, not just the current one, but this is the intended usage.


User

[demo](https://jsfiddle.net/HTMLGuyLLC/Lzp5w3rg) | [back to top](#whatsincluded)

A generic user class with properties for id, name, email, phone, etc - also allows for front-end permission checks

Method/PropertyParamsReturnNotes
constructordata:objectself
getIdstring/int
setIdid:string/intthis
getIsGuestboolif your site has users who don't login but still interact and have a user record (like guest checkout)
setIsGuestis_guest:boolthis
setIsAdminboolif your site has users who have ultimate permissions and you want to do something based on that
setIsGuestis_admin:boolthis
getUsernamestring
setUsernameusername:stringthis
getFnamestring
setFnamefname:stringthis
getLnamestring
setLnamelname:stringthis
getNamestringreturns fname and lname concatenated with a space
getEmailstring
setEmailemail:stringthis
getPhonestring
setPhonephone:stringthis
getPermissionsarray
setPermissionspermissions:arraythis
addPermissionpermission:string/intthis
removePermissionpermission:string/intthis
hasPermissionpermission:string/intbool
getAdditionalDataobjectset any additional data about this user that doesn't fit the default getters and setters here (a better idea would be to extend this object with your custom properties/methods)
setAdditionalDatadata:objectthis
getDataItemkey:stringmixedreturns a single value from the additional data object/array
setDataItemkey:string, val:mixedsets a single value in the additional data array/object
populatedata:objectthissets provided values all at once (id, isGuest, isAdmin, etc)
Instantiation with current user data:

The easy way:

Create an object named $user with values from your server

<script>
const $user = {
    id: <?php echo $user['id']; ?>,
    fname: "<?php echo $user['fname']; ?>",
    //..
    permissions: JSON.parse("<?php echo json_encode($user['permissions']); ?>"),
    additionalData: JSON.parse("<?php echo json_encode([
        'user_type'=>$user['user_type'],
        //whatever else you might want to pass
    ]); ?>"),
    //..
};
</script>

Then instantiate the User class in your JS file somewhere

const cur_user = new User($user);
cur_user.getId();

@see: /examples/CurrentUserSingleton for a method of instantiating the current user once and using everywhere Note: Even though that creates a singleton which is available anywhere, it's still highly recommended that you pass that object to functions and methods where it is used (dependency injection)

The harder way:

Perform an XHR request to grab site details via a JSON API, then run the populate method on the site object.

import {User} from '@htmlguyllc/jpack/es/user';
 
$.get('/my-user-info-endpoint.php', function(data){
    //don't forget error handling!
    const cur_user = new User(JSON.parse(data));
});

Of course you can use this class for any User not just the current one, but that's the intended usage.


Strings

[demo](https://jsfiddle.net/HTMLGuyLLC/ebof3hm4/) | [back to top](#whatsincluded)

Contains methods for semi-common string manipulation like creating a getter from a string ('hi' = 'getHi')

Method/PropertyParams (name:type)ReturnNotes
ucfirststring:stringstringcapitalizes the first letter of a string like ucfirst in PHP
getterstring:stringstringcreates a getter method name from a string
setterstring:stringstringcreates a setter method name from a string
To Use:
import {strings} from '@htmlguyllc/jpack/es/strings';

strings.ucfirst('bob'); //returns 'Bob'
strings.getter('name'); //returns 'getName';
strings.setter('name'); //returns 'setName';

DOM

[demo](https://jsfiddle.net/HTMLGuyLLC/et42sLbm/) | [back to top](#whatsincluded)

Has methods for converting just about anything into a native DOM Element or array of them (you can provide a string selector, jQuery object, native DOM object, etc). Also has some shortcuts for common DOM checks/manipulation (like removing an element, verifying an element exists in the DOM, or replacing an element with HTML)

Method/PropertyParams (name:type)ReturnNotes
getElementel:mixed, error_on_none:bool, error_on_multiple:boolElement/HTMLDocument/nullreturns a native DOM element for whatever you provide (selector string, array of elements, single element, jQuery wrapped DOM element, etc)
getElementsel:mixed, error_on_none:boolarraysame as getElement, except it returns all matches
removeel:mixed, error_if_not_found:boolthisremoves elements from the DOM - uses .getElements()
replaceElWithHTMLel:mixed, html:string, error_if_not_found:boolElementreplaces an element in the DOM with HTML and returns a reference to the new Element
existsel:mixedboolchecks to see if it exists in the DOM
multipleExistel:mixedboolchecks to see if more than 1 instance exists in the DOM
isVisibleel:mixed, error_if_not_found:bool, error_on_multiple:boolboolchecks to see if the provided element is visible
To Use:
import {dom} from '@htmlguyllc/jpack/es/dom';

//Dont do this. Most of these are dumb examples.
dom.getElement('.my-fav-button', true, true); //will throw an error if it doesn't find it, or if it finds more than 1
dom.getElements('.links', true); //will throw an error if none are found
dom.getElement('.my-button'); //returns the button, or null (if multiple, it returns the first)
dom.getElements('.links'); //returns an array of any matches for .links
dom.getElement($('a')); //returns the native DOM element for the link and removes the jQuery wrapper
dom.getElement(document.querySelectorAll('a')); //returns the first anchor

dom.exists('a'); //returns true if there is an anchor on the page
dom.multipleExist('a'); //returns true if more than 1 anchor on the page

Type Checks

[demo](https://jsfiddle.net/HTMLGuyLLC/5p9q1ofj/) | [back to top](#whatsincluded)

Validate the value of a variable with higher specificity than built-in functions. For instance, you can validate an object contains specific keys and throw errors if not, or if it contains keys that you didn't define

Method/PropertyParams (name:type)ReturnNotes
isDataObjectvalue:object, keys:array, require_all_keys:bool, block_other_keys:bool, throw_error:boolboolvalidates that an object contains data and not a dom element, array, null or anything else that would normally return true when you call typeof
To Use:
import {type_checks} from '@htmlguyllc/jpack/es/type_checks';

var my_obj = {id:null, name:'John Doe', email:'john@doe.com'};

//make sure my_obj contains the keys: 'id', 'name', 'email'
//force all keys to exist
//block any keys that aren't in that list
//throw an error if the object fails any checks
type_checks.isDataObject(my_obj, ['id', 'name', 'email'], true, true, true);

Events

[demo](https://jsfiddle.net/HTMLGuyLLC/wv2hkzp5/) | [back to top](#whatsincluded)

Includes methods for attaching event handlers including shorthand methods which create handlers that prevent the browser's default action (onclick, onsubmit)

Method/PropertyParams (name:type)ReturnNotes
setGlobalnamespace:string/nullselfadds each of the following functions to the global scope, a namespace is optional, but recommended. Use at your own risk! These may cause conflicts!
onClickel:mixed, callback:functionhandler:functionprevents the browser's default so you can handle link clicks and form submissions with less code - returns an updated handler in case you need to remove it later
onSubmitel:mixed, callback:functionhandler:functionsame as .onClick() but for submit - returns an updated handler in case you need to remove it later
onEventPreventDefaultel:mixed, event:string, callback:functioncallback:functiongenerates and attaches a handler which prevents the default action - returns the updated handler in case you need to remove it later
onel:mixed, event:string, callback:functionarrayattaches an event listener
offel:mixed, event:string, callback:functionarrayremoves an event listener
triggerel:mixed, event:string, event_options:mixedarraytriggers an event on an element/elements - uses .getElements()
To Use:
import {events} from '@htmlguyllc/jpack/es/events';

var preventedHandler = events.onClick('a.my-link', function(){
   //do something without the page redirecting to the href 
});
//now remove that handler
events.off('a.my-link', 'click', preventedHandler);

var handler = events.onSubmit('form.my-form', function(){
   //do something and submit the form using XHR 
});

//trigger submit on a form and pass an object as additional data in the event
events.trigger('.my-form', 'submit', {id:1});
Setting with a custom namespace (or no namespace):
import {events} from '@htmlguyllc/jpack/es/events';

events.setGlobal();

onClick('a', function(){
   //do something - href is prevented! 
});

ToggleOnMobile

[demo](https://jsfiddle.net/HTMLGuyLLC/68og394L/) | [back to top](#whatsincluded)

Toggle an element's visibility when you click a button. By default, the element is visible, but if the button is visible, the element will be hidden until the button is clicked. If the element is visible and the user clicks outside of it, the element is hidden. If the window is resized, the element will be shown or hidden based on visibility of the button.

Method/PropertyParams (name:type)ReturnNotes
constructorbtn:mixed, toggle_el:mixed, toggle_class:string, hide_on_outside_click:boolself
initselfattaches event handlers and immediately adjusts the visibility
destroyselfremoves event handlers - does not change the class
To Use:
import {ToggleOnMobile} from '@htmlguyllc/jpack/es/toggle';

const toggle = new ToggleOnMobile('.toggle-sidebar-btn', '.sidebar', 'visible', true);

toggle.init();

//and later if you want to, toggle.destroy();

Keywords

FAQs

Package last updated on 17 Jul 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc