Categories
Uncategorized

Drag Drop ES6

The following code demonstrates drag drop functionality in ES6.

<script>
  const onDrop = (e) => {
    e.preventDefault();
 e.target.appendChild(document.getElementById(e.dataTransfer.getData('target')));
  };
  const onDragOver = (e) => e.preventDefault();
  const onDragStart = (e) => e.dataTransfer.setData('target', e.target.id);
  
</script>
<div id="dest" ondrop="onDrop(event)" ondragover="onDragOver(event)" style="height: 200px; width: 200px; border: 1px solid #000; padding: 10px; box-sizing: border-box;"></div>
<img id="source" draggable="true" ondragstart="onDragStart(event)" src="http://via.placeholder.com/180x180" />

Demo

Categories
Uncategorized

Loader ES6

The following is the implementation of a simple Javascript (ES6) loader.

<script>
  const load = () => {
    let width = 0;
    const id = setInterval(() => {
      if (width === 100)
        clearInterval(id);
      else
        document.getElementById('bar').style.width = `${++width}%`;
    }, 10);
  };
</script>
<div id="loader" style="height: 100px; width: 600px; border: 1px solid #000;">
  <div id="bar" style="background-color: green; width: 0; height: 100px;" class="">
  </div>
</div>
<button onclick="load()">Load</button>

Demo

Categories
Uncategorized

Add Events ES6

In the example below, we create a button and attach a click event to it.

const button = document.createElement('button');
 button.innerHTML = 'Click';
 document.body.appendChild(button);
 const test = (val) => {
   console.log('clicked ' + val);
 };
 button.addEventListener('click', test.bind(this, 'test'));

Demo

Categories
interview

Debounce (ES6)

Sometimes, we would like to wait a certain minimum time period before successive method calls. For example in events like onscroll(), onresize(), this can go a long way in terms of optimizing the page performance as a whole.

The wrapping of the methods using a Debounce method is a simple way to achieve the desired result.

const debounce = (fn, interval) => {
  let timeout;
  return (...rest) => {
    if (timeout)
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        fn.apply(this, rest);
      }, interval);
  };
}

const test = (inp) => {
  console.log(inp);
};

const db = debounce(test, 1000);
const cb = () => {
  db('test');
};
const button = document.createElement('button');
button.innerHTML = 'fire';
document.body.appendChild(button);
button.addEventListener('click', cb);

Demo