diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 0f6040b..45671e6 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -220,6 +220,35 @@ const data = domManager.read('.para', true); console.log(data); ``` +## addEvent() usage + +This function is used to `add events` to specific HTML element. It takes four parameters like `selector` (can be id, class), `event` (can be any events like click, onchange,mouseover), `eventHandler` (must be a callback function) and `all`(default is false). + +```javascript +import { event } from './index.js'; + +const { addEvent } = event(); + +// adds "click" event to button with id "button". +addEvent("#button","click",()=>{console.log("clicked")},false); +``` + +The `selector` and `event` must be in string, `all` must be in boolean. + +If `all` is set to true , the function adds the event to all HTML elements matching the selector. + +```javascript +import { event } from './index.js'; + +const { addEvent } = event(); + +const clickHandler = ()=>{console.log("clicked")}; + +// adds "click" event to ALL the buttons with class "button". +addEvent(".button", "click", clickHandler, true); +``` + +The callback function can be imported from any other `.js`file also. # domManager Module diff --git a/index.js b/index.js index 20f285a..5e65485 100644 --- a/index.js +++ b/index.js @@ -170,6 +170,41 @@ const deleteContent = () => { export { deleteContent }; +const event = () => { + const addEvent = (selector, event, eventHandler, all = false)=>{ + const el = !all + ? document.querySelector(selector) + : document.querySelectorAll(selector); + + if(typeof(selector) !== 'string' || typeof(event) !== 'string' || typeof(all) !== 'boolean'){ + throw new Error("Parameter type is invalid"); + } + + if (!el || el.length === 0) { + console.error('invalid selector'); + throw new Error('invalid selector'); + } + + if(typeof(eventHandler) !== "function"){ + throw new Error("Event handler must be a callback function"); + } + + if(!all){ + el.addEventListener(event, eventHandler); + } + + if(all){ + el.forEach((element)=>{ + element.addEventListener(event, eventHandler); + }); + } + + }; + return { addEvent }; +}; + +export { event }; + const createStyleSheet = (() => { const addStyle = (el, declaration) => { for (const val of Object.entries(declaration)) {