Last active
November 20, 2024 21:49
-
-
Save DevMasterX/0e73c72db1b45587de07dc53c3aea758 to your computer and use it in GitHub Desktop.
MODULE - create markup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createMarkup(arr, list, options = {}) { | |
// Default options | |
const { imgWidth = 300 } = options; | |
if (!Array.isArray(arr)) { | |
throw new Error('Invalid argument: "arr" should be an array.'); | |
} | |
if (!(list instanceof HTMLElement)) { | |
throw new Error('Invalid argument: "list" should be a valid DOM element.'); | |
} | |
// Generate markup based on array content | |
const markup = arr.length | |
? arr | |
.map( | |
({ id, img, name }) => ` | |
<li data-id="${id}" class="js-card"> | |
<img src="${img}" alt="${name}" width="${imgWidth}" /> | |
<h2>${name}</h2> | |
<p><a class="js-info" href="#">More information</a></p> | |
<div> | |
<button class="js-favorite">Add to favorite</button> | |
<button class="js-basket">Add to basket</button> | |
</div> | |
</li> | |
` | |
) | |
.join('') | |
: ` | |
<li> | |
<img | |
src="https://thumbs.dreamstime.com/b/empty-wicker-basket-black-white-isolated-white-background-basket-empty-wicker-basket-basket-vector-icon-black-white-302325782.jpg" | |
alt="404" | |
width="600" | |
/> | |
</li> | |
`; | |
// Insert generated markup into the target list element | |
list.innerHTML = markup; | |
} | |
export { createMarkup }; | |
//---------------USAGE | |
//import { createMarkup } from './helpers/createMarkup.js'; | |
// const listElement = document.querySelector('#my-list'); | |
// const items = [ | |
// { id: 1, img: 'https://example.com/image1.jpg', name: 'Item 1' }, | |
// { id: 2, img: 'https://example.com/image2.jpg', name: 'Item 2' }, | |
// ]; | |
// createMarkup(items, listElement, { imgWidth: 500 }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment