Code Monkey home page Code Monkey logo

vanillajs-browser-helpers's Introduction

This package has been moved to @jsfns/web and is no longer maintained in this repository.

Vanilla JS Browser helpers

This is a collection of simple, no dependency, vanilla JS snippets with the aim of making it easier to work with vanilla JS.

They is written in ES6, since most of the major browsers support this syntax, all scripts have however been converted into the Echma Script 5 syntax (without polyfills) and stored in the ./es5 folder if needed.

Polyfills haven't been included as they exist in abundance on NPM, and since the need for polyfills are ever diminishing it is more future proof and clutter free to leave them out.

GENERAL HELPERS

These helpers are browser specific, for more general helpers check out: vanillajs-helpers

Documentation

Documentation is written in the Wiki of the GitHub repository, but here below is an overview of the helpers available.

Helpers

Method Description
addClass Add class to a DOM element
after Insert HTML or ad DOM element after a DOM element
append Insert HTML or ad DOM element into the end of a DOM element child list
attr Get/set an attribute of a DOM element
before Insert HTML or ad DOM element before a DOM element
children Get the direct child DOM elements of a DOM element
create Creates DOM element from CSS selector
css Get/set styling of a DOM element
create Creates a DOM element from a selector (eg. div#myDiv.some-class)
data Get/set value of a data attribute on a DOM element
delegate Bind delegate event(s) to a DOM element
domReady Bind a handler to the document ready event
elmIndex Get the index of a DOM node amongst its siblings
eventPlus Sophisticated on/off event bindings:
- Remove all events
- Event name spacing
- Delegates
find Find method that detect the most efficient find method depending on the query. Also includes certain wildcards.
findByClass Find DOM elements by class name
findById Find DOM element by ID
findByName Find DOM elements by name attribute
findByQuery Find DOM elements using CSS query
findByTagName Find DOM elements by tag name
hasClass Detect if a DOM element has a given class
hidden Detect if a DOM element is hidden or not
inDOM Detect if a DOM element is inserted into the DOM
inView Detect if a DOM element is in view on the screen
invisible Detect if a DOM element is invisible or not
isDOMChildNode Detect if a DOM element is a child node of another DOM element
isDOMContainer Detect if a DOM node is a can contain child nodes
isDocument Detect if a DOM node is the document node
isDOMElement Detect if a DOM node is a DOM element
isDOMFragment Detect if an object is a document fragment
isDOMNode Detect if a DOM node is actually a DOM node
isDOMRoot Detect if a DOM node is the root element (body in HTML)
isWindow Detect if an Object is a window object
matches Detect if a DOM node match a given CSS selector
off Remove event handler from a DOM element
on Add event handler to a DOM element
once Add a single fire event handler to a DOM element
position Get the position of a DOM element
prefixed Prefixes a name with vendor prefixes (webkit, moz, ms, o)
prepend Insert HTML or ad DOM element into the beginning of a DOM element child list
remove Remove a given DOM element from the DOM
removeClass Remove a given class name from a DOM element
replace Replace a given DOM element with another
scrollBy Scroll page or given DOM element by x number of pixels left/right
scrollInfo Get information about current window or DOM element scroll positions (includes percentage scrolled)
scrollParent Get the current DOM elements scrolling parent
scrollTo Scroll page or given DOM element to given x and y coordinate
siblings Get the siblings of a DOM element
size Get the size of a DOM element
supportsCSS Detects whether the current browser supports a given CSS prop and/or value
toDOM Convert a HTML string into DOM element(s)
toggleClass Toggle a class from a DOM element
trigger Trigger an event handler on a DOM element
viewport Get the current viewport area
visible Detect if a DOM element is visible or not

Installation

npm install vanillajs-browser-helpers

Usage

// ES 6
import append from 'vanillajs-browser-helpers/append';
append('<div class="child-element"></div>');
// ES 5
var append = require('vanillajs-browser-helpers/es5/append').default;
append('<div class="child-element"></div>');

Something missing?

If you find any bugs or missing functionality you would like to see included, feel free to add an issue in the issue list or perhaps do a Pull Request of a great snippet you created.

Testing

Check out the Testing docs

vanillajs-browser-helpers's People

Contributors

dependabot[bot] avatar tokimon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

coddent

vanillajs-browser-helpers's Issues

Detect document visibility

Add a visibility change event and a method to detect document visibility.
With fallback to focus/blur if the other event is not supported

`delegateHandler` needs event type that includes `delegateTarget`

in a usage I had to hack the type a bit to make TS accept e.delegateTarget:

const onClick = delegateHandler(`.${fileTileContainer}`, (e: Event) => {
  const { delegateTarget: thumb } = e as Event & { delegateTarget: Element };
  dispatch('thumbclick', { thumb });
});

function inView

La fonction inView vérifie si l'élément est dans le viewport. Il serais intéressant d'avoir une option pour savoir si l’élément est dans la vue et est visible (exemple dans un div avec overflow:hidden, inView renvoi true car l'élément est dans le viewport mais il n'est pas visible)

'Data' cache storage for elements

Store data associated with the element, that is not compatible with the 'data-' attribute.
Like jQuery.

(could be used by eventPlus)

Optimized on scroll

Optimize by using requestAnimationFrame and by taking idle time into account (cancelling the polling after a certain time)

Optimized resize handler

Use requestAnimationFrame to optimize the resize reaction time and with a idle timer (cancelling the polling)

Add `data`

Function to add data linked to dom element (like jQuery.data()):

const _cache = new WeakMap()

function elmData (elm, key, data) {
  let elmCache = _cache.get(elm)

  if (!key) { return elmCache }

  if (data) {
    if (!elmCache) {
      elmCache = {}
      _cache.set(elm, elmCache)
    }

    elmCache[key] = data
  }

  return elmCache && elmCache[key]
}

export default elmData

Add `wrap`

to wrap an element in given HTML:

function findEmptyElm (elm) {
  const child = elm && elm.firstElementChild
  return child ? findEmptyElm(next) : elm
}

export default (elm, html) => {
  elm.insertAdjacentHTML('afterend', html)
  const insertElm = findEmptyElm(elm.nextElementSibling)
  insertElm && insertElm.appendChild(elm)
}

CJS files are not using 'vanillajs-helpers/cjs' files

Once a CJS file is transpiled all references of vanillajs-helpers will still use the es6 version, thus not avoiding the need for transpilation.

eg for isString the compiled output is:

var _isString = require('vanillajs-helpers/isString');

But optimally it should be

var _isString = require('vanillajs-helpers/cjs/isString').default;

A simpler way to avoid this problem needs to be found.

Clarify installation

I am having issues getting the module to work. I ran the install code and it installed correctly; however, I can't seem to get the code to work in my browser.

Notification.js
`
import inView from 'vanillajs-browser-helpers/es5/inView.js'; //I tried these classes and the es6 varient
import addClass from 'vanillajs-browser-helpers/es5/addClass.js';
import removeClass from 'vanillajs-browser-helpers/es5/removeClass.js';

let notification = document.getElementById('notification');
let notificationTrigger = document.getElementById('notification-trigger');

if (notification != null && notificationTrigger != null) {

if (inView(notificationTrigger) != true) {
	removeClass(notification, "visible",);
} else {
	addClass(notification, "visible",);
}

}
But when I have<Script src="notification.js" type="module"> </script>` I get an error in the console about relative paths. Maybe it's my limited exposure to javascript or limited understanding of node. But could you build a short sample website to help clarify how to get it running beyond just NPM install?

Add create method

Should create a new element of the desired tag, but should also create it from given CSS selector string (like jQuery)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.