JS - Other

Create A Link

var link = 'Name'.link('url');

Cursor Tracker

<style>
  .tracker {
    position: fixed;
    transform: translate(-50%, -50%);
    width: 40px;
    z-index: 9999;
    pointer-events: none;
    transition: all .15s;
  }

  .tracker image {
    width: 100%;
    height: 100%;
  }
</style>

<body>
  <div class="tracker">
    <img src="ImagePath" />
  </div>
</body>

<script>
var timer;
  $(document).ready(function () {
    $("body")[0].addEventListener("mousemove", e => {
      clearTimeout(timer);
      timer = setTimeout(() => {
        $(".tracker").css("left", `${e.pageX}px`);
        $(".tracker").css("top", `${e.pageY}px`);
      }, 300);
    })
  })
</script>

Deep Copy

const deepCpy = (obj) =>{
  JSON.parse(JSON.stringify(obj))
}

Detect browser or tab closing

window.addEventListener('beforeunload', function (e) {
  e.preventDefault();
  e.returnValue = '';
});

Detect Device Type

const dectectDeviceType = () =>
    /Andriod|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? "mobile" : "desktop";
console.log(dectectDeviceType);

Detect print event

var mediaQueryList = window.matchMedia('print');

mediaQueryList.addListener(function(mql) {
  if (mql.matches) {
    console.log('onbeforeprint equivalent');
  } else {
    console.log('onafterprint equivalent');
  }
});

Detecting changes in forms

var $form, origForm;
var isChanged = false;

$(document).ready(function () {
    $form = $('#formID');
    origForm = $form.serialize();
    isChanged = false;

    //check if form changed
    $('#formID :input').on('change input', function () {
        isChanged = true;
    });

    //check if html element changed
    $(`#elementID`).on('DOMSubtreeModified', function () {
        isChanged = true;
    });
})

$("#cancelButton").click(function () {
    if (isChanged) {
        //prompt message to user
    }
    else {
        //continue to cancel action
    }
})

Device Memory API

We can Determine the amount of Ram a Device Has by using Navigator.deviceMemory in JS

const memory = navigator.deviceMemory;
console.log(`${memory} GB`)

Dynamic Property Names

const dynamic = 'flavor';
var item = {
   name: 'Coke',
   [dynamic]: 'Cherry'
}


Result : { name: 'Coke', flavor: 'Cherry' }

Empty an Array

array.length = 0;

Extract Unique Values

var uniqueEntries = [...new Set(array)];

File Download via AJAX

$('#ID').on('click', function () {
  $.ajax({
    url: 'requestURL',
    method: 'GET',
    xhrFields: {
      responseType: 'blob'
    },
    success: function (data) {
      var a = document.createElement('a');
      var url = window.URL.createObjectURL(data);
      a.href = url;
      a.download = 'FILENAME.EXTENSION';
      document.body.append(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
    }
  });
});