Highly recommended 10 short practical JavaScript code Snippets _javascript Tips

Source: Internet
Author: User

JavaScript is becoming more and more popular, it has become the first choice for front-end development, and using JavaScript based Nodejs, we can also develop high-performance back-end services, and even I see in the hardware programming domain also appeared JavaScript figure. JavaScript is evolving into a versatile language of development.

But it's not easy to use JavaScript. In addition to mastering its syntax and knowing how to write high quality code, you need to understand how to solve the requirements scenarios that are encountered in almost every project, such as: Date of judgment, highlighting text, limiting characters, etc., and many third-party libraries can solve these problems , but these libraries may not be just created to solve this problem, which means you need to introduce a lot of irrelevant code that will make your entire system bloated and also affect the performance of your system. My approach is to collect and use those common JavaScript snippets and use them as much as possible first when needed. Here are 10 snippets of practical JavaScript code I've collected, based on which you can also create more powerful JS plug-ins or functional functions.

1. Determine whether 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 want a very simple function instead of introducing a large third-party library. At this point, you can use the following date to verify 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 provid ed 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 (de

 LIMITER);

 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 &&//Che
 CK 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. Gets the maximum width or height of a group of elements
The following function is useful for developers who need to perform dynamic typesetting.

 var getmaxheight = function ($elms) {
 var maxheight = 0;
 $elms. Each (the function () {
 //In some cases your 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's third-party libraries that can implement highlighted text, but I prefer to use this small piece of JavaScript code to implement this feature, it is very short, and can be adapted to my needs to be flexible, and can define the highlighted style. The following two functions can help you create your own text highlighting plug-ins.

 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 + ' class= ' highlight ">$&</' + 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 PHR ASEs to highlight
 ' strong '//custom tag)
; 

4. Text Dynamic effect
Sometimes you want to give your text a bit more action, so that each word moves. You can use the jquery plug-in code below 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 class= "letter" >$&</span> "));
 $this. Find (' Span.letter '). Each (function (i, EL) {
  settimeout (function () {$ (EL). addclass (Klass);}, delay * i);
 });
 });

}; 

How to use:
$ (' P '). Animatetext (' 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 list elements, you can achieve good results.

 $.fn.fadeall = function (OPS) {
 var o = $.extend ({
 delay:500,//delay between elements speed:500
 ,//Animat Ion 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 following script allows you to intercept text based on a given character length, and if the text is intercepted, it is automatically 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 appropriate layout
at present, many designs have adopted a responsive layout to fit the Web site or the display of applications on different devices. You often need to determine in your code which screen adapter is currently under.

 function Isbreakpoint (BP) {
 //The breakpoints that your set in your css
 var bps = [, 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 ()) {
 //breakpoint at or less
}
if (Isbreakpoint ()) {
 //breakpoint bet Ween and ...
 

8. Global Count
in some games or ad scenes, you need to record the number of times a user clicks 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
  $ (IT). 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 need to dynamically create menus, drop-down lists, or list items. Here is a piece of the most basic code to implement the above functions, 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 VA Lue if present
  item + ' </' + child + ' > ';
 }

 Return ' < ' + parent + ' > ' + items.join (') + ' </' + parent + ' > ';
} 

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 ']
); 

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

Related Article

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.