Code Snippets

JS copy-all-html


copy("<!DOCTYPE html>\n<html lang='en'>\n"+document.getElementsByTagName('html')[0].innerHTML+"\n");
    

JS getSelectedValue()


function getSelectedValue(ele) {
  let select = document.getElementById(ele);
  let selectedValue = select.value;
  return selectedValue;
}
  

CSS smooth-scroll


html { scroll-behavior: smooth; }

JS copy-to-clipboard.mjs


function copyFromElement(copy, ele, fldType = "text") {
  function getPos(curLeft, curTop) {
    this.curLeft = curLeft;
    this.curTop = curTop;
  }

  function getOffset(objFind) {
    let rect = document.querySelector(objFind).getBoundingClientRect();
    let curTop = rect.top + window.scrollY;
    let curLeft = rect.left + window.scrollX;
    const curButton = new getPos(curLeft, curTop);
    return curButton;
  }

  function addMsg(ele, msg) {
    let getPos = getOffset(ele);
    let newMsg = document.createElement("div");
    newMsg.setAttribute("id", "showMsg");
    newMsg.innerHTML = msg;
    newMsg.setAttribute(
      "style",
      ` background:#5fca36;
        color:white;
        padding:0.25rem;
        font-weight:bold;
        text-align:center;
        font-family: sans-serif;
        position:fixed;
        border-radius:5px;
        font-size:0.85rem;
        text-shadow: 1px 1px black;
        top: ${getPos.curTop - window.scrollY + 22}px;
        left:${getPos.curLeft - window.scrollX + 22}px;
        max-width: 200px;
        width: auto`
    );
    document.querySelector(ele).insertAdjacentElement("afterend", newMsg);
    // ele.insertAdjacentElement('afterend', newMsg);
    setTimeout(function () {
      document.querySelector(ele).parentNode.removeChild(newMsg);
    }, 2500);
  }

  const copyToClipboard = (str) => {
    if (navigator && navigator.clipboard && navigator.clipboard.writeText)
      return navigator.clipboard.writeText(str);
    return Promise.reject("The Clipboard API is not available.");
  };

  // "copy" needs to be document.querySelector() format
  if (fldType === "text") {
    copyToClipboard(document.querySelector(copy).innerHTML);
  } else if (fldType === "innerText") {
    copyToClipboard(document.querySelector(copy).innerText);
  } else {
    copyToClipboard(document.querySelector(copy).value);
  }
  addMsg(ele, "Copied to Clipboard!");
  }

 function attachEventListener(eleID, fldType = "text") {
   document.getElementById(eleID).addEventListener('click', (item) => {
     // console.log('message #1');
     // console.log("item.target.id = " + item.target.id);
     // console.log('item.target.getAttribute("data-copyFromElement") = ' + item.target.getAttribute("data-copyFromElement"));
     let dataCopyFromElement = item.target.getAttribute("data-copyFromElement")
     document.getElementById(dataCopyFromElement).setAttribute('style', `outline:1px solid #009900;font-style:italic;color:#444;background-color:#5fca36`);
     setTimeout(() => {
       document.getElementById(dataCopyFromElement).setAttribute('style', 'outline:none;font-style:normal;color:inherit')
     }, 2500);
     copyFromElement(`#${dataCopyFromElement}`, `#${item.target.id}`, fldType);
   });
 }

/* This code block was written for the Code Snippets App specifically 
function attachEventListener(eleID, fldType = "text") {
  document.getElementById(eleID).addEventListener('click', (item) => {
    console.log("eleID = " + eleID);
    copyFromElement(`#${eleID}`, `#${eleID}`, "innerText");
  });
}
*/

export {
  copyFromElement,
  attachEventListener
}

/* =================================================
// Here's how you use it in your application. First the HTML 
// The key piece here is the 'data-copyFromElement="copyIt"' part
---------------------------------------------------------
<textarea name="copyIt" id="copyIt" class="copyIt" cols="80" rows="5">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad rerum eligendi adipisci.
</textarea><br>
<button id="copy" class="copy" data-copyFromElement="copyIt">Copy Textarea</button><br>

<input type="text" name="copyIt2" id="copyIt2" class="copyIt" size="80" value="whatever..."/>
<button id="copy2" class="copy" data-copyFromElement="copyIt2">Copy Text</button><br>
<div id="copyIt3">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad rerum.</div>  
<button id="copy3" class="copy" data-copyFromElement="copyIt3">Copy InnerHTML</button><br>

// Then you attach an event listener
// 1st param is whatever the ID is 
// 2nd param depends on the element being copied
// default is for ele.innerHTML otherwise it's ele.value
attachEventListener('copy', "ta");
attachEventListener('copy2', "ta");
attachEventListener('copy3');
attachEventListener('copy4');
*/

JS css-vars.mjs


// Get the root element
let root_var = document.querySelector(":root");
// Create a function for getting a variable value
function cssVar_get(_var, clg = 0) {
  // Get the styles (properties and values) for the root
  let root_var_style = getComputedStyle(root_var);
  // Alert the value of the --blue variable
  if (clg === 1) {
    console.log(
      `The value of --${_var} is: ` +
      root_var_style.getPropertyValue(`--${_var}`)
    );
  }
  return root_var_style.getPropertyValue(`--${_var}`);
}
// Create a function for setting a variable value
function cssVar_set(_var, _val, _locStg = 0) {
  root_var.style.setProperty(`--${_var}`, `${_val}`);
  if (_locStg !== 0) {
    localStorage.setItem(`${_var}`, `${_val}`);
  }
}

export {
  root_var,
  cssVar_set,
  cssVar_get
};

/*========== Usage Example ==================
// cssVar_get(_var,clg=0);
// cssVar_set(_var, _val, 1);
/*==== END "CSS VARIABLES" FUNCTIONALITY =====*/

JS slider-togle.mjs


function sliderToggle(getID, init = "none") {
let slideUp = (target, duration = 750, render = "flex") => {
  target = document.querySelector(target);
  target.style.transitionProperty = "height, margin, padding";
  target.style.transitionDuration = `${duration}ms`;
  target.style.boxSizing = "border-box";
  target.style.height = `${target.offsetHeight}px`;
  target.offsetHeight;
  target.style.overflow = "hidden";
  target.style.height = 0;
  target.style.paddingTop = 0;
  target.style.paddingBottom = 0;
  target.style.marginTop = 0;
  target.style.marginBottom = 0;
  window.setTimeout(() => {
    target.style.display = "none";
    target.style.removeProperty("height");
    target.style.removeProperty("padding-top");
    target.style.removeProperty("padding-bottom");
    target.style.removeProperty("margin-top");
    target.style.removeProperty("margin-bottom");
    target.style.removeProperty("overflow");
    target.style.removeProperty("transition-duration");
    target.style.removeProperty("transition-property");
  }, duration);
};

let slideDown = (target, duration = 750, render = "flex") => {
  target = document.querySelector(target);
  target.style.removeProperty("display");
  let display = window.getComputedStyle(target).display;
  if (display === "none") display = render;
  target.style.display = display;
  let height = target.offsetHeight;
  target.style.overflow = "hidden";
  target.style.height = 0;
  target.style.paddingTop = 0;
  target.style.paddingBottom = 0;
  target.style.marginTop = 0;
  target.style.marginBottom = 0;
  target.offsetHeight;
  target.style.boxSizing = "border-box";
  target.style.transitionProperty = "height, margin, padding";
  target.style.transitionDuration = duration + "ms";
  target.style.height = height + "px";
  target.style.removeProperty("padding-top");
  target.style.removeProperty("padding-bottom");
  target.style.removeProperty("margin-top");
  target.style.removeProperty("margin-bottom");
  window.setTimeout(() => {
    target.style.removeProperty("height");
    target.style.removeProperty("overflow");
    target.style.removeProperty("transition-duration");
    target.style.removeProperty("transition-property");
  }, duration);
};

let slideToggle = (target, duration = 500, render = "flex") => {
  let _target = document.querySelector(target);
  let display = window.getComputedStyle(_target).display;
  if (display === "none") {
    return slideDown(target, duration, render);
  } else {
    return slideUp(target, duration, render);
  }
};

function toggleIcon(ele) {
  ele = document.querySelector(ele);
  if (ele.classList.contains("close")) {
    ele.classList.remove("close");
    ele.classList.add("open");
  } else {
    ele.classList.remove("open");
    ele.classList.add("close");
  }
}

function createSlideToggleCss() {
  const slide_toggle_style = `
  :root {
    --icon-close-svg1: url(https://css.netcentrx.net/icons/icon_close_v01.svg);
    --icon-open-svg1: url(https://css.netcentrx.net/icons/icon_open_v01.svg);
    --icon-size: 12px;
  }
  body {
    background-color:#046;
  }

  * {
    box-sizing: border-box;
  }

  .target {
    padding: 0.5em;
    background-color: #fefefe;
    margin-bottom: 0.25em;
    text-align: left;
    color: rgba(50, 50, 50, 0.95);
    font-weight: 450;
    border-radius: 0 0 5px 5px;
    display: flex;
    width:100%;
    border: 1px solid #aaa;
    background: #fff;
  }

  .center {
    width: 550px;
    margin: 0 auto;
    text-align: center;
  }
  h3.slide-trigger {
    width: 100%;
    margin: 0 auto;
    border: 1px solid gray;
    color:#444;
    text-shadow: 0.5px 0.5px #777, 1px 1px #aaa;
    user-select: none;
    padding: 0.25rem;
    font-size: 1rem;
    text-shadow: 0.5px 0.5px #999, 1px 1px #aaa;
  }
  .slide-trigger {
    font-size: 1rem;
    cursor: pointer;
    background: #eee;
  }
  .icon.open {
    background: var(--icon-open-svg1);
    width: var(--icon-size);
    height: var(--icon-size);
    background-size: var(--icon-size);
    display: inline-block;
    padding-right: 0.5rem;
    transform: rotate(180deg);
    transition: 1s;
    filter: invert(51%) sepia(3%) saturate(2%) hue-rotate(322deg) brightness(97%)
      contrast(84%);
  }
  .icon.close {
    background: var(--icon-close-svg1);
    width: var(--icon-size);
    height: var(--icon-size);
    background-size: var(--icon-size);
    display: inline-block;
    padding-right: 0.5rem;
    transform: rotate(-180deg);
    transition: 1s;
    filter: invert(51%) sepia(3%) saturate(2%) hue-rotate(322deg) brightness(97%)
      contrast(84%);
  }
  .color-fill {
    filter: invert(51%) sepia(3%) saturate(2%) hue-rotate(322deg) brightness(97%)
      contrast(84%);
  }
  .triggers {
    text-align: center;
    width: clamp(450px, 800px, 90vw);
    margin: 0 auto;
    border-radius: 6px;
    font-family: sans-serif;
    overflow:hidden;
    box-shadow:2px 2px #99999975;
  }`;

  const slide_toggle_style_tag = document.createElement('style');
  slide_toggle_style_tag.setAttribute('id', 'slide_toggle');
  slide_toggle_style_tag.innerHTML = slide_toggle_style;
  // document.head.insertAdjacentHTML("afterbegin", slide_toggle_style_tag);
  document.head.appendChild(slide_toggle_style_tag);
}

if (init === "none") {
  document.querySelector(`#${getID} ~ .target`).style.display = 'none';
  document.querySelector(`#${getID} > .icon`).classList.add('open');
  document.querySelector(`#${getID} > .icon`).classList.remove('close')
}
document.getElementById(getID).addEventListener("click", function () {
  slideToggle(`.${getID}`);
  toggleIcon(`#${getID} .icon`);
});
if (document.getElementById('slide_toggle')) {
  console.log('createSlideToggleCss() only called once');
} else {
  createSlideToggleCss();
  console.log('createSlideToggleCss() called for the first time');
}
}

export {
  sliderToggle
};

CSS :: @property


@property --my-prop {
  syntax: "<color>";
  inherits: false;
  initial-value: #c0ffee;
}

window.CSS.registerProperty


window.CSS.registerProperty({
  name: "--my-prop",
  syntax: "<color>",
  inherits: false,
  initialValue: "#c0ffee"
});

pdo.php.mysql.ex



<?php
//Create connection
$db = new PDO('mysql:host=localhost;dbname=DATABASENAME;charset=utf8mb4', 'USERNAME', 'PASSWORD');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//https://www.php.net/manual/en/pdo.setattribute.php

//Check connection status
echo $db->getAttribute(PDO::ATTR_CONNECTION_STATUS);

//SELECT with loop
$select = $db->prepare("SELECT `col`, `col2` FROM `table`");
$select->execute();
while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
  $db_col = $row['col'];
  $db_col2 = $row['col2'];
  echo "$db_col $db_col2
"; } //SELECT with loop AND WHERE $select = $db->prepare("SELECT `name` FROM `table` WHERE `status` = :status;"); $select->execute(array(':status' => $status)); while ($row = $select->fetch(PDO::FETCH_ASSOC)) { $db_name = $row['name']; echo "$db_name
"; } //SELECT with WHERE one value $uid = 1610; $select = $db->prepare("SELECT `col`, `col2`, `col3` FROM `table` WHERE `uid` = :uid LIMIT 1;"); $select->execute(array(':uid' => $uid)); $row = $select->fetchAll(PDO::FETCH_ASSOC); $col = $row[0]['col']; //SELECT one row $select = $db->prepare("SELECT `col` FROM `table` WHERE `id` = :the_id LIMIT 1;"); $select->execute(array(':the_id' => $id)); $row = $select->fetch(); $id = $row['id']; //SELECT with WHERE shorter $select = $db->prepare("SELECT `col`, `col2` FROM `table` WHERE `id` = :id;"); $row = $select->fetch($select->execute(array(':id' => $id))); //fetch for one/first row fetachAll for many/all rows //SELECT simple $select = $db->prepare("SELECT `col`, `col2`, `col3` FROM `table`"); $select->execute(); $row = $select->fetch(); $db_col = $row['col']; $db_col2 = $row['col2']; $db_col3 = $row['col3']; //SELECT with WHERE $select = $db->prepare("SELECT `col`, `col2`, `col3` FROM `table` WHERE `id` = :id"); $select->execute(array(':id' => $value)); $row = $select->fetch(); $db_col = $row['col']; $db_col2 = $row['col2']; //Bind Param $select = $db->prepare("SELECT `col` FROM `table` WHERE `id` = :id AND `first_name` = :fname"); $select->bindParam(':id', $id, PDO::PARAM_INT);//https://www.php.net/manual/en/pdo.constants.php $select->bindParam(':fname', $first_name, PDO::PARAM_STR); $select->execute(); //Count returned columns $select = $db->prepare("SELECT `col` FROM `table` WHERE `col` = :id"); $select->execute(array(':id' => $id)); $column_count = $select->columnCount();//Column count //Check if row exists $select = $db->prepare("SELECT `col` FROM `table` WHERE `col` = :id"); $select->execute(array(':id' => $id)); $result = $select->fetchColumn(); if ($result > 0) { echo "Row has been found"; } else { echo "No row in DB"; } //Get last inserted id $id = $db->lastInsertId(); //INSERT $insert = $db->prepare('INSERT INTO `table` (`col`, `col2`) VALUES (?, ?)'); $insert->execute(["$value", "$value2"]); $insert = $db->prepare('INSERT INTO `table` (`col`, `col2`, `col3`, `col4`, `col5`, `col6`, `col7`, `col8`, `col9`, `col10`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); $insert->execute(["$value", "$value2", "$value3", "$value4", "$value5", "$value6", "$value7", "$value8", "$value9", "$value10"]); $insert = $link->prepare('INSERT INTO `table` (`col`, `col2`, `col3`) VALUES (:avalue, :avalue2, :avalue3)'); $insert->execute([ 'avalue' => '1', 'avalue2' => $value2, 'avalue3' => $value3, ]); //INSERT shorter form $data = [];//an array $db->beginTransaction(); $stmt = $db->prepare("INSERT IGNORE INTO `table` (`col`, `col2`, `col3`) VALUES (?,?,?)"); for ($i = 0; $i < count($data); $i++) { $stmt->execute($data[$i]); } $db->commit(); //INSERT with UPDATE on duplicate $query = $db->prepare('INSERT INTO table (col, col2, col3) VALUES(:var, :var2, :var3) ON DUPLICATE KEY UPDATE col = :var, col2 = :var2, col3 = :var3'); $query->bindParam(':var', $avar, PDO::PARAM_INT); $query->bindParam(':var2', $avar2, PDO::PARAM_STR); $query->bindParam(':var3', $avar3, PDO::PARAM_STR); $query->execute(); //UPDATE on WHERE $update = $db->prepare("UPDATE `table` SET `col` = 1 WHERE `col2` = :the_value"); $update->execute(array(':the_value' => $value)); //UPDATE on WHERE 2 $update = $db->prepare("UPDATE `table` SET `col` = :update_to WHERE `col2` = :the_value"); $update->execute(array(':update_to' => $update_to, ':the_value' => $value)); //UPDATE $update = $db->prepare("UPDATE `table` SET `col` = 1"); $update->execute(); //DELETE $delete = $db->prepare("DELETE FROM `table` WHERE `col2` = :the_value"); $delete->execute(array(':the_value' => $value));

createConstFromIDs()


  <section>
    <div class="row"><label for="padding" class="bold">padding</label><label class="small-label" for="padding">normal</label><label class="small-label" for="padding">hover</label></div>
    <div class="row"><label for="padding-top-normal">top</label><input type="text" value="10" class="small-text" id="padding-top-normal"><input type="text" value="10" class="small-text" id="padding-top-hover"></div>
    <div class="row"><label for="padding-right-normal">right</label><input type="text" value="10" class="small-text" id="padding-right-normal"><input type="text" value="10" class="small-text" id="padding-right-hover"></div>
    <div class="row"><label for="padding-bottom-normal">bottom</label><input type="text" value="10" class="small-text" id="padding-bottom-normal"><input type="text" value="10" class="small-text" id="padding-bottom-hover"></div>
    <div class="row"><label for="padding-left-normal">left</label><input type="text" value="10" class="small-text" id="padding-left-normal"><input type="text" value="10" class="small-text" id="padding-left-hover"></div>
    <div class="row"><label for="padding-height">height</label><input type="text" value="10" class="small-text" id="padding-height-normal"><input type="text" value="10" class="small-text" id="padding-height-hover"></div>
    <div class="row"><label for="padding-width">width</label><input type="text" value="10" class="small-text" id="padding-width-normal"><input type="text" value="10" class="small-text" id="padding-width-hover"></div>

  </section>
  <section>
    <div class="row"><label for="margin" class="bold">margin</label><label class="small-label" for="margin">normal</label><label class="small-label" for="margin">hover</label></div>
    <div class="row"><label for="margin-top-normal">top</label><input type="text" value="10" class="small-text" id="margin-top-normal"><input type="text" value="10" class="small-text" id="margin-top-hover"></div>
    <div class="row"><label for="margin-right-normal">right</label><input type="text" value="10" class="small-text" id="margin-right-normal"><input type="text" value="10" class="small-text" id="margin-right-hover"></div>
    <div class="row"><label for="margin-bottom-normal">top</label><input type="text" value="10" class="small-text" id="margin-bottom-normal"><input type="text" value="10" class="small-text" id="margin-bottom-hover"></div>
    <div class="row"><label for="margin-left-normal">top</label><input type="text" value="10" class="small-text" id="margin-left-normal"><input type="text" value="10" class="small-text" id="margin-left-hover"></div>
    <div class="row"><label for="margin-height">height</label><input type="text" value="10" class="small-text" id="margin-height-normal"><input type="text" value="10" class="small-text" id="margin-height-hover"></div>
    <div class="row"><label for="margin-width">width</label><input type="text" value="10" class="small-text" id="margin-width-normal"><input type="text" value="10" class="small-text" id="margin-width-hover"></div>
  </section>
<aside>
  <button class="btn">Test Button</button><button class="btn">Test Button</button>
  <br><br>  
  <button class="test-button" onclick="createConstFromIDs()">create const from Element IDs</button>
</aside>

<script>
/*===================================
* The function below does the following:
* 1) find all element IDs in a document
* 2) create textarea field 
* 3) insert a "const" for all IDs into textarea
* 4) embed at bottom of page
* 5) scroll to the bottom of page
* 6) set focus to textarea field
* 7) select all text in textarea field 
*----------------------------------*/
function createConstFromIDs() {
  let allIDs;
  document.querySelectorAll("[id]").forEach((item) => {
    allIDs += `const ${item.id.replaceAll('-','_')} = document.getElementById('${item.id}');\n`;
    // allIDs += `${item.id.replaceAll('-','_')}.value\n`;
    // allIDs += `${item.id.replaceAll('-','_')}\n`;
  });
  let _create_const = document.createElement('textarea');
  _create_const.setAttribute('id', 'create_const_from_ids');
  _create_const.setAttribute('style', 'width: 96%;height:200px;font-size:0.65rem;color:#0000ff;background:#f2f8ff;');
  document.body.insertAdjacentElement("beforeend", _create_const);
  create_const_from_ids.innerHTML = allIDs.replace('undefined', '');
  create_const_from_ids.scrollIntoView();
  setTimeout(function() {
    create_const_from_ids.focus();  
    create_const_from_ids.select();
  }, 2500);
}
createConstFromIDs();
</script>
  

Add New Snippet