JavaScript Tricks

Home / Coding Tricks / JavaScript Tricks

Random Hex Color

'#'+Math.floor(Math.random()*16777215).toString(16);

Scroll to Hash and Highlight (jQuery)

function scrollToHashAndHighlight (hash) { // hash is in the form '#divId'

  $('html, body').animate({

    scrollTop: $(hash).offset().top - 50

  }, 2000, function () {

    $(hash).effect("highlight", {}, 3000);

  });

}

DOM Ready

document.addEventListener("DOMContentLoaded", function(event) {
  // Your code ...
});

Capture Keyboard Keys (jQuery)

$(document).keyup(function(e) {
  if (e.keyCode === 27) { /* Your code */ } // ESC
  if (e.keyCode === 37) { /* Your code */ } // LEFT
  if (e.keyCode === 39) { /* Your code */ } // RIGHT
});

Short Date

var month = ('0' + (dateObj.getMonth() + 1)).slice(-2);
var date  = ('0' + dateObj.getDate()).slice(-2);        
var year  = dateObj.getFullYear();
         
var shortDate = year + '-' + month + '-' + date;

Output: 2018-08-13

Markup Interpolation (AngularJS v1.x)

var app = angular.module('myApp', []);

app.config(function($interpolateProvider) {
  $interpolateProvider.startSymbol('[{');
  $interpolateProvider.endSymbol('}]');
});

Input: [{ firstName }]
Output: Ahsan

Leave a Reply

Your email address will not be published. Required fields are marked *