/ Gists

Gists

On gists

Money price object

AW

demo.php #

<?php

//App\PriceModule\Model\Currency $currency
// Money\Money $amount

// vytvoreni money objektu
	$amountFrom = $this->currency->convertPrice(
			$this->currency->parsePrice($activeRow->currency_id, $activeRow->amount_from)
		);

// vetsi nebo rovno
$amount->greaterThanOrEqual($amountFrom)

// odecteni
/** @var \Money\Money */
$priceAfterDiscount = $price->getPrice()->subtract($discount)->getAmount(); 

// nastaveni objektu ceny 
$price->setPrice($priceAfterDiscount)

// raw data jako string vcetne haliru napr 50000 // 500kc
/** @var \Money\Money */
$moneyObject->getAmount()

On gists

Detect outside click

JavaScript

outsideclick.js #

const elem = document.querySelector('div');
elem.addEventListener('click', (e) => {
 const outsideClick = !elem.contains(e.target);
  
 console.log(outsideClick); //returns true or fasle
});

On gists

Drag drop

JavaScript

demo.html #

<!-- https://jsbin.com/rideqiloge/edit?html,output -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Drag and Drop Effect in JavaScript</title>

    <!-- Add some CSS Code -->
    <style>
      * {
        margin: 0px;
        padding: 0px;
      }
      body {
        background-color: black;
        height: 100vh;
        width: 100%;
      }
      .container {
        display: flex;
        justify-content: space-around;
        align-items: center;
        flex-wrap: wrap;
        height: 100vh;
        width: 100%;
      }
      .whiteBox {
        width: 150px;
        height: 150px;
        background-color: white;
        border: none;
        border-radius: 50%;
      }
      .imgBox {
        background: url("https://images.unsplash.com/photo-1469474968028-56623f02e42e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=874&q=80") no-repeat center center;
        height: 100%;
        width: 100%;
        background-size: cover;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: grid;
        place-items: center;
      }
      .hold {
        border: 4px solid white;
      }
      .hide {
        display: none;
      }
    </style>
  </head>
  <body>

    <div class="container">
      <div class="whiteBox" id="box">
        <div class="imgBox" draggable="true"></div>
      </div>
      <div class="whiteBox" id="box"></div>
      <div class="whiteBox" id="box"></div>
      <div class="whiteBox" id="box"></div>
      <div class="whiteBox" id="box"></div>
    </div>

    <!-- Let's start to write script -->
    <script>

      // Access the HTML Elements
      let imgBox = document.querySelector(".imgBox");
      let whiteBoxes = document.getElementsByClassName("whiteBox");


      // When user start to drag the element ( Here, imgBox )
      // Event listeners for dragable imgBox element
      imgBox.addEventListener("dragstart", (e) => {

        e.target.className += " hold";
        setTimeout(() => {
          e.target.className = "hide";
        }, 0);
      });

      // When user ready to drop the element 
      imgBox.addEventListener("dragend", (e) => {
        e.target.className = " imgBox";
      });

      // Iterate all the white boxes
      for (Boxes of whiteBoxes) {
        Boxes.addEventListener("dragover", (e) => {
          e.preventDefault();
        });

        Boxes.addEventListener("drop", (e) => {
          e.target.append(imgBox);
        });
      }
    </script>
  </body>
</html>

On gists

Stacks / Queue

JavaScript

stack.js #

class Stack {
    #items = []

    push(item) {
        this.#items.push(item)
    }

    pop() {
        if(this.isEmpty()) return 'Underflow'
        return this.#items.pop()
    }

    isEmpty() {
        return this.#items.length === 0
    }

    get length() {
        return this.#items.length
    }

    getItems() {
        return this.#items
    }

    prettify() {
        let resultString = ''
        for(let i = 0; i < this.#items.length; i++)
            resultString += this.#items[i] + ' '
        return resultString
    }
}

let foods = new Stack

foods.push('pizza')
foods.push('hamburger')
foods.push('kebab')
foods.push('kufte')

console.log(foods.length) // 4

console.log(foods.getItems()) // [ 'pizza', 'hamburger', 'kebab', 'kufte' ]

console.log(foods.prettify()) // pizza hamburger kebab kufte

console.log(foods.pop()) // kufte
console.log(foods.pop()) // kebab
console.log(foods.pop()) // hamburger
console.log(foods.pop()) // pizza

console.log(foods.length) // 0

On gists

Simple global state hook aka composable

Vue.js

state.js #

import { ref, readonly } from 'vue';

const sharedVar = ref(false);

const toggleOutside = () => {
  sharedVar.value = !sharedVar.value;
};

export const useTestState = () => {
  const toggleInside = () => {
    sharedVar.value = !sharedVar.value;
  };

  return {
    sharedVar: readonly(sharedVar),
    toggleOutside,
    toggleInside,
  };
};

On gists

Animations

Tailwind CSS

demo.html #

<div class="flex justify-around p-20">
  <!-- Wiggle animation -->
  <div class="flex flex-col gap-4">
    <span>wiggle</span>
    <div class="h-16 w-16 animate-wiggle rounded-md bg-pink-400"></div>
  </div>

  <!-- heartBeat animation -->
  <div class="flex flex-col gap-4">
    <span>heartBeat</span>
    <div class="h-16 w-16 animate-heartBeat rounded-md bg-blue-400"></div>
  </div>

  <!-- flipHorizontal animation -->
  <div class="flex flex-col gap-4">
    <span>flipHorizontal</span>
    <div class="h-16 w-16 animate-hflip rounded-md bg-orange-400 text-center"><span>Flip H</span></div>
  </div>

  <!-- flipVertical animation -->
  <div class="flex flex-col gap-4">
    <span>flipVertical</span>
    <div class="h-16 w-16 animate-vflip rounded-md bg-indigo-400 text-center"><span>Flip V</span></div>
  </div>
</div>

<div class="flex justify-around p-20">
  <!-- Swing animation -->
  <div class="flex flex-col gap-4">
    <span>swing</span>
    <span class="animate-swing text-3xl font-extrabold text-red-400">Swinging</span>
  </div>

  <!-- rubberBand animation -->
  <div class="flex flex-col gap-4">
    <span>rubberBand</span>
    <span class="animate-rubberBand text-3xl font-extrabold text-violet-400">Stretching</span>
  </div>

  <!-- flash animation -->
  <div class="flex flex-col gap-4">
    <span>flash</span>
    <span class="animate-flash text-3xl font-extrabold text-orange-800">Flashing</span>
  </div>
</div>

<div class="flex justify-around p-20">
  <!-- headShake animation -->
  <div class="flex flex-col gap-4">
    <span>headShake</span>
    <span class="animate-headShake text-3xl font-extrabold text-green-500">Shaking Heads</span>
  </div>

  <!-- wobble animation -->
  <div class="flex flex-col gap-4">
    <span>wobble</span>
    <span class="animate-wobble text-3xl font-extrabold text-blue-500">Wobbling</span>
  </div>

  <!-- wobble animation -->
  <div class="flex flex-col gap-4">
    <span>jello</span>
    <span class="animate-jello text-3xl font-extrabold text-purple-400">Jello</span>
  </div>
</div>

On gists

Before, Prepend, Append, After (insertAdjacentElement) ... (*Text, *Html)

JavaScript

demo.html #

<!-- https://jsbin.com/pajoyovilu/3/edit?html,css,js,console,output -->


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
	
	
	<button onclick="placeTo('beforebegin')">before</button>
	<button onclick="placeTo('afterbegin')">prepend</button>
	<button onclick="placeTo('beforeend')">append</button>
	<button onclick="placeTo('afterend')">after</button>
	
	
	<div id="x">
		<div>START</div>
		<AA>aa</AA>
		<BB>bb</BB>
		<CC>cc</CC>
		<div>END</div>
		
	</div>
</body>
</html>

On gists

Card number - space after each 4 digit & only digit control

Vue.js

component.vue #

<!-- https://javascript.plainenglish.io/vue-get-input-value-206d5adc832c -->

<template>
  <div id="app">
    <input
      type="text"
      :value="cardNo"
      placeholder="Card number"
      @input="handleInput"
      @keypress="handleKeyPress"
    />
    <br />
  </div>
</template>
<script>
export default {
  data() {
    return {
      cardNo: '',
    };
  },
  methods: {
    handleInput(event) {
      this.cardNo = event.target.value
        // Remove spaces from previous value
        .replace(/\s/g, '')
        // Add a space after every set of 4 digits
        .replace(/(.{4})/g, '$1 ')
        // Remove the space after the last set of digits
        .trim();
    },
    handleKeyPress(event) {
      const num = Number(event.key);
      const value = event.target.value;
      // Only allow 16 digits
      if ((!num && num !== 0) || value.length >= 16 + 3) {
        event.preventDefault();
      }
    },
  },
};
</script>

On gists

Debounced method in Vue (settimeout), fetch with cors mode

JavaScript Vue.js

example.js #

  methods: {
    search() {
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        this.findSong()
      }, 500)
    },

    async findSong() {
      let headers = new Headers()
      headers.append('Content-Type', 'application/json')
      headers.append('Accept', 'application/json')
      headers.append('Origin', 'http://vue3.rjwebdesign.cz')
      headers.append('GET', 'POST', 'OPTIONS')

      let q = encodeURI(this.q)
      if (!this.q) {
        return
      }

      //console.log(q)
      // return

      const response = await fetch(`https://itunes.apple.com/search?term=${q}&limit=50`, {
        mode: 'cors',
        method: 'POST',
        headers: headers
      }).catch(err => console.log(err))

      const data = await response.json()
      this.songs = data.results.filter(item => item.kind == 'song')
      console.log(this.songs)
    },

On gists

ES6: Template system in literal

JavaScript ES 6

example.js #

let post = {
    title: 'JavaScript Template Literals',
    excerpt: 'Introduction to JavaScript template literals in ES6',
    body: 'Content of the post will be here...',
    tags: ['es6', 'template literals', 'javascript']
};


let {title, excerpt, body, tags} = post;

let postHtml = `<article>
<header>
    <h1>${title}</h1>
</header>
<section>
    <div>${excerpt}</div>
    <div>${body}</div>
</section>
<footer>
    <ul>
      ${tags.map(tag => `<li>${tag}</li>`).join('\n      ')}
    </ul>
</footer>`;

window['out'].innerHTML = postHtml