Minlib.js is small and simple javascript library to adding event listeners and searching elements by CSS selectors.
file (ES6) | weight |
---|---|
minlib.js | 0.658 KB |
minlib.min.js | 0.245 KB |
Include minlib.min.js on your page before the closing </body>
tag
<script src="/path/to/minlib.min.js"></script>
query() (Element.querySelector()
)
Function query()
returns the first element that is a descendant of the element on which it is invoked that matches the specified group of selectors.
Syntax:query(selector, baseElement)
If a baseElement is document, you don't have to write this.
query('h1'); // returns first h1 element (baseElement is document)
let el = query('.container'); // returns element with class container
query('h1', el); // returns first h1 element from el (baseElement is el)
query('header h1');
queryAll() (Element.querySelectorAll()
)
Function queryAll()
returns a Array (not NodeList) of all elements descended from the element on which it is invoked that matches the specified group of CSS selectors.
Syntax:queryAll(selector, baseElement)
In selector you can write:
- String with selector (example 1)
- String with selectors (example 2)
- Element (function returns array with this element)
- Array with elements (function returns this array)
If a baseElement is document, you don't have to write this.
queryAll()
returs Array so you should usefor...of
(or forEach()
)
queryAll('h1'); // returns array with all h1 elements (baseElement is document)
queryAll('h1, p') // returns array with all h1 and p elements
queryAll('h1', element); // returns array with all h1 elements from element (baseElement is element)
addEvent() (element.addEventListener
)
Syntax: addEvt(target,
type,
listener, useCapture)
In target you can write:
- Element (or a function that returns an element) (example 3, example 4, example 5, example 6)
- String with selector (example 1)
- String with selectors (example 2)
- Array with elements (example 6)
minlib.js:
addEvt('h1', 'click', yourFunction); // sets event listener on all h1 element
addEvent('h1, h2, p', 'click', yourFunction); // sets event listener on all h1 h2 and p element
In vanilla.js you have to write:
document.querySelectorAll('h1, h2, p').forEach(function (element) {
element.addEventListener('click', yourFunction);
});
addEvent(query('#row'), 'click', fuction () {
//code in anonymous function
});
addEvent(queryAll('.button')[1], 'click', yourFunction); // sets event listener on second element with button class
let el = query('.container');
addEvent(el, 'click', yourFunction);
let elOne = document.createElement('h1'),
elTwo = document.createElement('p');
addEvent([elOne, elTwo], 'click', yourFunction)
let div = document.createElement('div')
addEvent(div, 'click', yourFunction);
loaded() (load
)
function loaded()
fired when a resource and its dependent resources have finished loading.
Syntax: loaded(listener)
loaded(function(){
//code
});
The MIT License (MIT)