DEV Community

Brent Vanwildemeersch
Brent Vanwildemeersch

Posted on

[Series] JS Tips & Tricks - Ep. 1

Introduction

A lot of Javascript tips, tricks, and code snippets are widely available, but not always even easily accessible. In this series, I will post on a regular basis helpful code snippets, tips, tricks that I used or find useful for JS-development

Snippet 1 - RGB to Hex

Transforming an RGB-color value to a hexadecimal value is an easy task if you only have one color to convert, and a browser to find an online RGB(a) to hex transforming tool. But when you have multiple RGB values to convert, the next snippet makes life a lot easier.

function rgbToHex(r, g, b) {
  return ((r << 16) + (g << 8) + b).toString(16).padStart(6, "0");
}
Enter fullscreen mode Exit fullscreen mode

Snippet 2 - Array to HTML List

A short snippet to visualize array items into a HTML ordered or unordered list where the list items are dynamically added to the <ol></ol> or <ul></ul> tags

function arrayToHTMLList(array, listId) {
  let el = document.querySelector("#" + listID);
  return el.innerHTML += arr.map((item) => `<li>${item}</li>`).join("");
}
Enter fullscreen mode Exit fullscreen mode

Snippet 3 - Is bottom of page visible

Web-development sometimes requires you to trigger a set of events when the bottom of the page is reached. The boolean that is returned from the following function will let you know if the user has reached the bottom of the page or not.

function isBottomOfPageVisible() {
  return document.documentElement.clientHeight + window.scrollY >=
    (document.documentElement.scrollHeight || document.documentElement.clientHeight);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)