http://go.ad2up.com/afu.php?id=665574

10 JavaScript Code Snippets to Save Your Time

JavaScript Code Snippets to Save Your Time

JavaScript code snippets are the mind jiggling process for any web developer. You have to deal with enormous error, debug process and syntax checking before making a usable and working code snippet for web functionality. These are common problem, and you don’t have any specific detector of these kinds of problem, so need to be aware and efficient at your coding side to avoid time wasting process.

JavaScript libraries are known for pace development with lighter load time on web server, quick response with client side integration make it more robust and easy to implement scripting language. Despite all these features there are many challenges for web developers to mastering JavaScript coding, today’s we’re focusing on some kind of aid for you to save your valuable time while coding JavaScript.

Following 10 code snippets will redefine your web development path, you will be able to overcome usual mistakes while JavaScript Coding by using simple tactics. Use the following JavaScript Code Snippets to save your time and efforts.

 

Validating a Date Effectively

function isValidDate(value, userFormat) {

  // Set default format if format is not provided
  userFormat = userFormat || 'mm/dd/yyyy';

  // Find custom delimiter by excluding
  // month, day and year characters
  var delimiter = /[^mdy]/.exec(userFormat)[0];

  // Create an array with month, day and year
  // so we know the format order by index
  var theFormat = userFormat.split(delimiter);

  // Create array from user date
  var theDate = value.split(delimiter);

  function isDate(date, format) {
    var m, d, y, i = 0, len = format.length, f;
    for (i; i  0 && m  0 &&
      // Check if it's a valid day of the month
      d <= (new Date(y, m, 0)).getDate()
    );
  }

  return isDate(theDate, theFormat);
}

How to Use??

isValidDate('dd-mm-yyyy', '31/11/2012')

 

Highlighting text in a paragraph

function highlight(text, words, tag) {

  // Default tag if no tag is provided
  tag = tag || 'span';

  var i, len = words.length, re;
  for (i = 0; i < len; i++) {
    // Global regex to highlight all matches
    re = new RegExp(words[i], 'g');
    if (re.test(text)) {
      text = text.replace(re, '$&');
    }
  }

  return text;
}

How to Use??

$('p').html( highlight(
    $('p').html(), // the text
    ['foo', 'bar', 'baz', 'Lazy Dog'], // list of words or phrases to highlight
    'strong' // custom tag
));

 

Fading Elements One By One

$.fn.fadeAll = function (ops) {
  var o = $.extend({
    delay: 500, // delay between elements
    speed: 500, // animation speed
    ease: 'swing' // other require easing plugin
  }, ops);
  var $el = this;
  for (var i=0, d=0, l=$el.length; i<l; i++, d+=o.delay) {
    $el.eq(i).delay(d).fadeIn(o.speed, o.ease);
  }
  return $el;
}

How to Use??

$(elements).fadeAll({ delay: 300, speed: 300 });

 

Creating many types of menus

function makeMenu(items, tags) {

  tags = tags || ['ul', 'li']; // default tags
  var parent = tags[0];
  var child = tags[1];

  var item, value = '';
  for (var i = 0, l = items.length; i < l; i++) {
    item = items[i];
    // Separate item and value if value is present
    if (/:/.test(item)) {
      item = items[i].split(':')[0];
      value = items[i].split(':')[1];
    }
    // Wrap the item in tag
    items[i] = ''+ // add value if present
        item +'';
  }

  return ''+ items.join('') +'';
}

How to Use??

// Dropdown select month
makeMenu(
  ['January:JAN', 'February:FEB', 'March:MAR'], // item:value
  ['select', 'option']
);

// List of groceries
makeMenu(
  ['Carrots', 'Lettuce', 'Tomatos', 'Milk'],
  ['ol', 'li']
);

 

Easy “read more” with inline tags

function excerpt(str, nwords) {
  var words = str.split(' ');
  words.splice(nwords, words.length-1);
  return words.join(' ') + 
    (words.length !== str.split(' ').length ? '…' : '');
}

 

Embedding YouTube Videos from Links

function embedYoutube(link, ops) {

  var o = $.extend({
    width: 480,
    height: 320,
    params: ''
  }, ops);

  var id = /\?v\=(\w+)/.exec(link)[1];

  return '';
}

How to Use??

embedYoutube(
  'https://www.youtube.com/watch?v=JaAWdljhD5o', 
  { params: 'theme=light&fs=0' }
);

 

Counting clicks on a button

$(element)
    .data('counter', 0) // begin counter at zero
    .click(function() {
        var counter = $(this).data('counter'); // get
        $(this).data('counter', counter + 1); // set
        // do something else...
    });

 

Typewriter and highlighter effects with CSS3 transitions

$.fn.animateText = function(delay, klass) {

  var text = this.text();
  var letters = text.split('');

  return this.each(function(){
    var $this = $(this);
    $this.html(text.replace(/./g, '$&'));
    $this.find('span.letter').each(function(i, el){
      setTimeout(function(){ $(el).addClass(klass); }, delay * i);
    });
  });
};

How to Use??

$('p').animateText(15, 'foo');

 

Setting Breakpoints for Responsive Design

function isBreakPoint(bp) {
  // The breakpoints that you set in your css
  var bps = [420, 580, 668, 924];
  var w = $(window).width();
  var min, max;
  for (var i = 0, l = bps.length; i  min && w <= max;
}

How to Use??

if ( isBreakPoint(420) ) { 
  // breakpoint at 420 or less
}
if ( isBreakPoint(580) ) { 
  // breakpoint between 420 and 580
}
...

 

Maximum Width or Height In A Set Of Elements

var getMaxHeight = function ($elms) {
  var maxHeight = 0;
  $elms.each(function () {
    // In some cases you may want to use outerHeight() instead
    var height = $(this).height();
    if (height > maxHeight) {
      maxHeight = height;
    }
  });
  return maxHeight;
};

How to Use??

$(elements).height( getMaxHeight($(elements)) );