JavaScript is becoming more and more popular. It has become the first choice for front-end development. With NodeJS based on the JavaScript language, we can also develop high-performance back-end services. I have even seen JavaScript appear in the field of hardware programming. JavaScript is gradually evolving into an all-round development language.
But it is not easy to use JavaScript well. In addition to mastering its syntax and knowing how to write high-quality code, you also need to understand how to solve the needs scenarios that will be encountered in almost every project, such as: judging dates, highlighting text, limiting the number of characters, etc. There are many third-party libraries that can solve these problems, but these libraries may not be created just to solve this problem, which means you need to introduce a lot of irrelevant code, which will make your entire system bloated and will also affect the performance of the system. My approach is to collect and use those common JavaScript snippets and use them first whenever necessary. Below are 10 pieces of practical JavaScript code I have collected. Based on them, you can also create more powerful JS plug-ins or functional functions.
1. Determine whether the date is valid
The date function included in JavaScript is still too simple, and it is difficult to meet the needs of parsing and judging different date formats in real projects. JQuery also has third-party libraries to make date-related processing simple, but sometimes you may just need a very simple function without introducing a huge third-party library. At this time, you can use the following date verification 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 = 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 < 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 < 13 && 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 there are no 31 days in November
isValidDate('dd-mm-yyyy', '31/11/2012')
2. Get the maximum width or height of a set of elements
The following function is very useful for developers who need to perform 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 many third-party libraries of JQuery that can implement the function of highlighting text, but I prefer to use the following small piece of JavaScript code to implement this function. It is very short and can be flexibly modified according to my needs, and you can define the highlighting style yourself. 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 un-highlighted functions:
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 Motion Effect
Sometimes you want to add motion to a paragraph of your text so that every word can move. You can use the following jQuery plug-in 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 one by one
The following jQuery plug-in can hide a group of elements one by one according to the step length (interval time) you set. Used in reloading list elements can achieve good results.
$.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 the number of words in text
The script below allows you to intercept text according to the given character length. If the text is intercepted, 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 adaptability in the corresponding layout
Many designs have adopted responsive layouts to adapt to the display of the website or application on different devices. You often need to determine which screen adaptation you are currently in in the code.
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 game or advertising scenarios, you need to record the number of times the user clicks a button on the current page. At this time, you can use jQuery's .data() function to handle it:
$(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 allowedFullScreen="true" id="embedid" quality="high" 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 need to create menus, drop-down lists, or list items dynamically. The following is a piece of the most basic code to implement the above functions, and you can expand them accordingly according to actual needs.
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']);
The above is just a small part of those practical JavaScript code snippets. I also recommend that you pay attention to collecting or writing such basic code snippets yourself. They can be used in many projects or provide more complete functions through some modifications. Using these code snippets will save you a lot of development time.