Front End Benefits! 10 short but ultra-functional JavaScript snippets

Source: Internet
Author: User

JavaScript is becoming more and more popular, it has become the first choice for front-end development, and with the use of JavaScript-based Nodejs, we can also develop high-performance backend services, and even I see JavaScript in the field of hardware programming. JavaScript is evolving into an all-powerful development language. Here are the 10 useful JavaScript codes I've collected, based on which you can also create more powerful JS plugins or function functions.

But it's not easy to use JavaScript, and you need to know how to solve the requirements that are encountered in almost every project, such as judging dates, highlighting text, limiting the number of characters, and so on, in addition to mastering its syntax and knowing how to write high-quality code, and there are many third-party libraries that can solve these problems. , but these libraries may not have been created just to solve this problem, which means you need to introduce a lot of extraneous code that will make your entire system bloated and affect the performance of your system. My approach is to collect and use the common JavaScript snippets and use them as much as possible when needed.

1. Determine if the date is valid

The date function in JavaScript is too simple to meet the needs of parsing and judging different date formats in real projects. jquery also has some third-party libraries to make date-related processing easier, but sometimes you might just want a very simple function rather than a large third-party library. At this point, you can use the following date to validate the code, which allows you to customize the date format and verify the validity of the date.

  function Isvaliddate (value, Userformat) {//Set default format if format is not provided Userformat = Userfo Rmat | |  ' 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 (del  Imiter);  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 < Len; i++) {f = format[i];      if (/m/.test (f)) m = Date[i];      if (/d/.test (f)) d = date[i];    if (/y/.test (f)) y = date[i]; } return (M > 0 && m < && y && y.length = = 4 && d > 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:

The following call returns false because November does not have 31 days

isValidDate(‘dd-mm-yyyy‘, ‘31/11/2012‘)
2. Get the maximum width or height of a set of elements

The following function is useful for developers who need to make a dynamic layout.

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)) );
3. Highlight text

There are a lot of jquery third-party libraries can achieve the function of highlighting text, but I prefer to use this small piece of JavaScript code to achieve this function, it is very short, and can be based on my needs to make flexible changes, and can define the highlighted style. The following two functions can help you create your own text highlighting plugin.

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, ‘<‘+ tag +‘>$&</‘+ tag +‘>‘);    }  }  return text;}

You will also need to cancel the highlighted function:

function unhighlight(text, tag) {  // Default tag if no tag is provided  tag = tag || ‘span‘;  var re = new RegExp(‘(<‘+ tag +‘.+?>|<\/‘+ tag +‘>)‘, ‘g‘);  return text.replace(re, ‘‘);}

How to use:

$(‘p‘).html( highlight(    $(‘p‘).html(), // the text    [‘foo‘, ‘bar‘, ‘baz‘, ‘hello world‘], // list of words or phrases to highlight    ‘strong‘ // custom tag));
4. Text Dynamic effect

Sometimes you'll want to add a little bit of text to your story and get each word moving. You can use the following jquery plugin code to achieve this effect. Of course you need to combine a CSS3 transition style to achieve better results.

$.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, ‘<span>$&</span>‘));    $this.find(‘span.letter‘).each(function(i, el){      setTimeout(function(){ $(el).addClass(klass); }, delay * i);    });  });};

How to use:

$(‘p‘).animateText(15, ‘foo‘);
5. Hide elements Individually

The following jquery plugin can hide a set of elements individually based on the step size (interval) you set. Used in the reload of the list element to achieve a good result.

$.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 });
6. Limit text Count

The following script allows you to intercept text based on a given character length, and if the text is truncated, it will automatically be followed by an ellipsis.

function excerpt(str, nwords) {  var words = str.split(‘ ‘);  words.splice(nwords, words.length-1);  return words.join(‘ ‘) +    (words.length !== str.split(‘ ‘).length ? ‘…‘ : ‘‘);}
7. Determine the current suitability of the corresponding layout

Many designs have been designed with responsive layouts to fit the display of websites or applications on different devices. You often need to judge in your code which screen is currently in the appropriate degree.

function isBreakPoint(bp) {  // The breakpoints that you set in your css  var bps = [320, 480, 768, 1024];  var w = $(window).width();  var min, max;  for (var i = 0, l = bps.length; i < l; i++) {    if (bps[i] === bp) {      min = bps[i-1] || 0;      max = bps[i];      break;    }  }  return w > min && w <= max;}

How to use:

if ( isBreakPoint(320) ) {  // breakpoint at 320 or less}if ( isBreakPoint(480) ) {  // breakpoint between 320 and 480}…
8. Global Count

In some games or ad scenarios, you need to record the number of times a user taps a button on the current page, and you can use the jquery. Data () function to handle:

$(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...    });
9. Embed Youku video
function embedYouku(link, ops) {  var o = $.extend({    width: 480,    height: 320,    params: ‘‘  }, ops);  var id = /\?v\=(\w+)/.exec(link)[1];  return ‘<embed allowFullScreen="true" id="embedid"  quality="high" width="‘+o.width+‘" height="‘+o.height+‘" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" src="‘+id+‘?‘+o.ops‘"‘;}

How to use:

embedYouku(  ‘http://static.youku.com/v/swf/qplayer.swf‘,   {‘winType=adshow&VideoIDS=XMTE3NzQ0NTky&isAutoPlay=false&isShowRelatedVideo=false‘});
10. Create a dynamic menu or drop-down list

In many scenarios, we all need to dynamically create menus, drop-down lists, or list items. Below is a section of the most basic code implementation of the above features, you can according to the actual needs of the corresponding extension.

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] = ‘<‘+ child +‘ ‘+      (value && ‘value="‘+value+‘"‘) +‘>‘+ // add value if present        item +‘</‘+ child +‘>‘;  }  return ‘<‘+ parent +‘>‘+ items.join(‘‘) +‘</‘+ parent +‘>‘;}

How to use:

// Dropdown select monthmakeMenu(  [‘January:JAN‘, ‘February:FEB‘, ‘March:MAR‘], // item:value  [‘select‘, ‘option‘]);// List of groceriesmakeMenu(  [‘Carrots‘, ‘Lettuce‘, ‘Tomatos‘, ‘Milk‘],  [‘ol‘, ‘li‘]);
Summary:

These are just a few of the useful javascript snippets, and I recommend that you usually pay attention to collecting or writing your own base code snippets, which can be used in many projects or to provide better functionality through some transformation, and using these snippets will save you a lot of development time.

Front End Benefits! 10 short but ultra-functional JavaScript snippets

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.