SoFunction
Updated on 2025-04-09

Common functions for javascript (1)

List of main contents of the article:

1. Adjust the size of the picture, not distorted (FF IE compatible) / Cut the picture (overflow:hidden)
2. Control the number of text in the textarea area
3. Click to display a new window
4. The input box automatically becomes longer with the content
5. Add a favorite
6. Set up the home page
7. Jquery + Ajax determines whether the user exists
8. Determine whether the email format is correct
9. Comprehensively determine username (length, English fields, etc.)
10. News scrolling
11. Only positive integers are allowed (used by shopping cart) or positive numbers (positive integers and positive decimals)
12. Convert string to number
13. Determine the file format (get file suffix)
14. Intercept strings
15. Split string

Main content:
1. Adjust the size of the picture without distorting (FF IE compatible)

// Usage <img src="this_image_path.jpg" onload="DrawImage(this,450,450);" /> function DrawImage(ImgD,FitWidth,FitHeight){ 
 var image=new Image(); 
 =; 
 if(&gt;0 &amp;&amp; &gt;0){ 
  if(/&gt;= FitWidth/FitHeight){ 
  if(&gt;FitWidth){ 
   =FitWidth; 
   =(*FitWidth)/; 
  }else{ 
   =; 
   =; 
  } 
  } else{ 
  if(&gt;FitHeight){ 
   =FitHeight; 
   =(*FitHeight)/; 
  }else{ 
   =; 
   =; 
  } 
  } 
 } 
 } 

Cut by overflow:hidden:

function clipImage(o, w, h){ 
 var img = new Image(); 
  = ; 
 if( >0 && >0) 
 { 
 if(/ >= w/h) 
 { 
  if( > w) 
  {  
   = (*h)/; 
   = h; 
  //("style", "marginLeft:-" + ((-w)/2).toString() + "px"); 
  $(o).css("margin-left", "-"+((-w)/2).toString() + "px"); 
  } 
  else 
  { 
   = ; 
   = ; 
  }  
 } 
 else 
 { 
  if( > h) 
  { 
   = (*w)/; 
   = w; 
  //("style", "margin-top:-" + ((-h)/2).toString() + "px"); 
  //$(o).css("style", "margin-top:-" + ((-h)/2).toString() + "px"); 
  $(o).css("margin-top", "-"+((-h)/2).toString() + "px"); 
 } 
  else 
  { 
   = ; 
   = ; 
  }  
 } 
 } 
} 

Example:

<style type="text/css"> 
 ul{list-style:none;} 
 ul li{float:left;padding:1px;border:#ccc 1px solid;width:120px;height:120px;overflow:hidden;text-align:center;over-flow:hidden;} 
</style> 
<ul> 
 <li><img src="" onload="DrawImage(this,120,120);" /></li> 
 <li><img src="" onload="clipImage(this,120,120);" /></li> 
</ul> 

2. Control the number of text in the textarea area

<script> 
/** 
 * Calculate how many characters remain in a textarea (jQuery) 
 * @param string textarea 
 * @param int maxLength 
 * @param string div 
 */ 
function charsRemain(textarea, maxLength, div) { 
 var currentLength = $(textarea).val().length; 
 
 var charsLeft = maxLength - currentLength; 
 if (charsLeft < 0) { charsLeft = 0; } 
 
 $("#"+ div +"_charsRemain").html(charsLeft); 
 
 if (currentLength > maxLength) { 
 var fullText = $(textarea).val().substring(0, maxLength); 
 $(textarea).val(fullText); 
 } 
} 
 
/** 
 * Calculate how many characters remain in a textarea (javascript) 
 * @param string textarea 
 * @param int maxLength 
 * @param string div 
 */ 
function charsRemain(textarea, maxLength, div) { 
 var currentLength = ; 
 
 var charsLeft = maxLength - currentLength; 
 if (charsLeft < 0) { charsLeft = 0; } 
 
 (div +"_charsRemain").innerHTML = charsLeft; 
 
 if (currentLength > maxLength) { 
 var fullText = (0, maxLength); 
  = fullText; 
 } 
} 
</script> 
 
<textarea rows="5" cols="15" onkeyup="charsRemain(this, 250, 'textarea');"></textarea> 
 
<span >250</span> characters remaining 

3. Click to display a new window

//Popt-up windowfunction g_OpenWindow(pageURL, innerWidth, innerHeight) 
{ 
 var ScreenWidth =  
 var ScreenHeight =  
 var StartX = (ScreenWidth - innerWidth) / 2 
 var StartY = (ScreenHeight - innerHeight) / 2 
 var wins = (pageURL, 'OpenWin', 'left='+ StartX + ', top='+ StartY + ', Width=' + innerWidth +', height=' + innerHeight + ', resizable=yes, scrollbars=yes, status=no, toolbar=no, menubar=no, location=no') 
 (); 
} 

Java code:

&lt;script language="JavaScript"&gt; 
 // Automatic pop-up window var whatsNew = open('','_blank','top=50,left=50,width=200,height=300,' + 'menubar=no,toolbar=no,directories=no,location=no,' + 'status=no,resizable=no,scrollbars=yes'); 
 ('&lt;center&gt;&lt;b&gt;news&lt;/b&gt;&lt; /center&gt;'); 
 ('&lt;p&gt;this is a test'); 
 ('&lt;p&gt;deos address'); 
 ('&lt;p align="right"&gt;' + '&lt;a href="javascript:()"&gt;Close&lt;/a&gt;'); 
 (); 
&lt;/script&gt; 

Unfortunately, many browsers block popups, which you need to manually allow to see! The following is a forced pop-up window. The principle is to create a form and open it through post.

&lt;script language="javascript"&gt; 
 function ForceWindow (){ 
  = ; 
  = ("FORM"); 
  = "_blank"; 
  = "post"; 
 (, [0]); //XML DOM: The insertBefore() method can insert a new child node in front of an existing child node.  insertBefore(newchild,refchild) } 
 
  = function (sUrl){ 
  = sUrl; 
 (); 
 } 
 
  = new ForceWindow(); 
&lt;/script&gt; 
 
&lt;body onLoad="('/')"&gt; 
 &lt;div&gt; 
this is a test ! we will open the deographics's website~~ 
 &lt;/div&gt; 
&lt;/body&gt; 

Of course there is a better way

<script> 
 function openWin(){ 
 (url,window, "help:no;scroll:no;resizable:no;status:0;dialogWidth:420px;dialogHeight:200px;center:yes"); 
 } 
</script> 

4. The input box automatically becomes longer with the content

// input auto length 
 // <input name="words" size="2" maxlength="100" onkeyup="checkLength(this)"/><span >0</span> 
 
 function checkLength(which) { 
 var maxchar=100; 
 //var oTextCount = ("char"); 
 iCount = (/[^\u0000-\u00ff]/g,"aa").length; 
 if(iCount<=maxchar){ 
  // = "<font color=#FF0000>"+ iCount+"</font>"; 
   = '1px dotted #FF0000'; 
  =iCount+2; 
 }else{ 
  alert('Please input letter less than '+ maxchar); 
 } 
 } 

5. Add a favorite

// addfavorite 
 function addfavorite(){ 
 if (){ 
  ('/','deographics'); 
 }else if (){ 
  ('deographics', '/', ""); 
 } 
 } 

6. Set up the homepage

// setHomepage 
 function setHomepage(){ 
 if(){ 
   = 'url(#default#homepage)'; 
  ('/'); 
 }else if(){ 
  if(){ 
  try{ 
   ("UniversalXPConnect"); 
  }catch(e){ 
   alert(" The operation was refused by browser,if you want to enable this feature, please enter in the address column 'about:config', then, change '.codebase_principal_support' to 'true' "); 
  } 
  } 
  var prefs = ['@/preferences-service;1'].getService(); 
  ('','/'); 
 } 
 }

7. Jquery + Ajax determines whether the user exists

// Check whether the username exists$("#username").blur(function(){ 
 var name = $(this).val(); var table = $(this).attr('title'); 
 if(name!=''){ 
 var dataString = 'username='+ name + '&amp;table=' + table; 
 $.post("",dataString,function(data){ //alert(data); 
  if(data==0){ 
  alert('This username already exist !'); $(this).val('').focus(); return false; 
  } 
 }); 
 } 
}); 

or

var datastring = 'id=' + $id + '&pos=' + $pos; 
$.ajax({ 
 type: "POST", 
 url: url, 
 data: dataString, 
 beforeSend: function(){}, 
 error: function(){alert('Send Error !');}, 
 success: function(data) { 
 // do something 
 } 
 }); 

8. Determine whether the email format is correct

function chekemail(temail){ 
 var pattern = /^[\w]{1}[\w\.\-_]*@[\w]{1}[\w\-_\.]*\.[\w]{2,4}$/i; 
 if((temail)){return true;}else{return false;} 
} 

9. Comprehensive judgment of username (length, English fields, etc.)

// Example var username = $('#username'); 
 var backValue = VerifyInput('username'); 
 
 if(backValue == 'length'){ 
 alert("Username is make up of 3 - 15 characters!"); 
  (); 
  return false; 
 }else if(backValue == 'first'){ 
 alert("the First character must be letter or number !"); 
  (); 
  return false; 
 }else if(backValue == 'back'){ 
 alert("Username only contains letter number or '_' "); 
  (); 
  return false; 
 } 
// judge function VerifyInput(user){ 
 var strUserID = $('#'+user).val(); 
 if ( &lt; 3 ||  &gt; 15){ 
  return 'length'; 
 }else{ 
  for (nIndex=0; nIndex&lt;; nIndex++){ 
  cCheck = (nIndex); 
  if ( nIndex==0 &amp;&amp; ( cCheck =='-' || cCheck =='_') ){ 
     return 'first'; 
    } 
  if (!(IsDigit(cCheck) || IsAlpha(cCheck) || cCheck=='-' || cCheck=='_' )){ 
     return 'back'; 
    } 
  } 
 } 
 } 
 function IsDigit(cCheck) {return (('0'&lt;=cCheck) &amp;&amp; (cCheck&lt;='9'));} 
 function IsAlpha(cCheck) {return ((('a'&lt;=cCheck) &amp;&amp; (cCheck&lt;='z')) || (('A'&lt;=cCheck) &amp;&amp; (cCheck&lt;='Z')))} 

10. News scrolling

<style type="text/css"> 
ul,li{margin:0;padding:0;font-size:12px;color:#999;} 
ul{height:100px;overflow:hidden;} 
ul li{line-height:20px;height:20px;} 
</style> 
 
<ul > 
 <li>New York web design Inc.1</li> 
 <li>Your site will be structured 2</li> 
 <li>hat will communicate the 3</li> 
 
 <li>hat will communicate the 4</li> 
 <li>hat will communicate the 5</li> 
 <li>hat will communicate the 6</li> 
 <li>hat will communicate the 7</li> 
 <li>hat will communicate the 8</li> 
 <li>hat will communicate the 9</li> 
 
 <li>New York web design Inc. 10</li> 
 <li>New York web design Inc.11</li> 
 <li>New York web design Inc. 12</li> 
 <li>New York web design Inc. 13</li> 
 <li>New York web design Inc. 14</li> 
</ul> 

Java code

// Usage: The four parameters are: operation object, residence time, relative speed (small, faster), and how much scrolling each time (it is best consistent with Li's Line-height). 
scroll('news', 3000, 1, 20 ); 
 
function scroll(element, delay, speed, lineHeight) { 
 var numpergroup = 5; 
 var slideBox = (typeof element == 'string')?(element):element; 
 var delay = delay||1000; 
 var speed=speed||20; 
 var lineHeight = lineHeight||20; 
 var tid = null, pause = false; 
 var liLength = ('li').length; 
 var lack = numpergroup-liLength%numpergroup; 
 for(i=0;i&lt;lack;i++){ 
 (("li")); 
 } 
 var start = function() { 
  tid=setInterval(slide, speed); 
 } 
 var slide = function() { 
  if (pause) return; 
   += 2; 
  if (  % lineHeight == 0 ) { 
  clearInterval(tid); 
  for(i=0;i&lt;numpergroup;i++){ 
   (('li')[0]); 
  } 
   = 0; 
  setTimeout(start, delay); 
  } 
 } 
 =function(){pause=true;} 
 =function(){pause=false;} 
 setTimeout(start, delay); 
} 

11. Only positive integers are allowed (used by shopping cart)

&lt;script language="JavaScript" type="text/javascript"&gt; 
function checkNum(obj){ 
 var re = /^[1-9]\d*$/; 
 if (!()){ 
 alert("Only positive integers are allowed!"); 
 =''; 
 (); 
 return false; 
 } 
} 
&lt;/script&gt; 
 
&lt;input name="rate" type="text"onkeyup="checkNum(this)" /&gt; 

Or positive number

&lt;script language="JavaScript" type="text/javascript"&gt; 
 function clearNoNum(obj) 
 { 
 //Replace all non-digits first, except for the numbers and.  = (/[^\d.]/g,""); 
 //The first one must be guaranteed to be a number instead of.  = (/^\./g,""); 
 //Certificate that only one appears, but no more.  = (/\.{2,}/g,"."); 
 //Please guarantee. It only appears once, but not more than twice  = (".","$#$").replace(/\./g,"").replace("$#$","."); 
 } 
&lt;/script&gt; 

Text boxes that can only enter numbers and decimal points: <input onkeyup="clearNoNum(this)">
12. Convert string to number

/*
 js provides two conversion functions: parseInt() and parseFloat().  The former converts the value into an integer, and the latter converts the value into a floating point number.  Only by calling these methods on the String type can these two functions run correctly; the returned NaN(Not a Number) for other types. 
 */ 
 
parseInt("1234blue"); //returns 1234 
parseInt("0xA"); //returns 10 
parseInt("22.5"); //returns 22 
parseInt("blue"); //returns NaN 
 
parseFloat("1234blue"); //returns 1234.0 
parseFloat("0xA"); //returns NaN 
parseFloat("22.5"); //returns 22.5 
parseFloat("22.34.5"); //returns 22.34 
parseFloat("0908"); //returns 908 
parseFloat("blue"); //returns NaN 
 
/*
 Type casting can also be used to process the types of converted values.  Use casting to access a specific value, even if it is of another type. 
 Boolean(value) - converts the given value into Boolean type;
 Number(value) - converts the given value into a number (can be an integer or a floating point number);
 String(value) - converts the given value into a string. 
 */ 
 
Boolean(""); //false – empty string 
Boolean("hi"); //true – non-empty string 
Boolean(100); //true – non-zero number 
Boolean(null); //false - null 
Boolean(0); //false - zero 
Boolean(new Object()); //true – object 
 
Number(false) 0 
Number(true) 1 
Number(undefined) NaN 
Number(null) 0 
Number( "5.5 ") 5.5 
Number( "56 ") 56 
Number( "5.6.7 ") NaN 
Number(new Object()) NaN 
Number(100) 100 
 
var s1 = String(null); //"null" 
var oNull = null; 
var s2 = (); //won't work, causes an error

 13. Determine the file format (get file suffix)

// Usage: get_ext(this,'img'); 
function get_ext(name){ 
 var pos = ('.'); 
 var extname = (pos,) // like: ('.') 
 var lastname = (); 
 
 if (lastname !='.jpg' &amp;&amp; lastname !='.gif' &amp;&amp; lastname !='.png' &amp;&amp; lastname !='.bmp'){ 
  return lastname; 
 }else{ 
  return name; 
 } 
 } 
} 

14. Intercept the string

// Simple 
&lt;script type="text/javascript"&gt; 
 
var str="Hello world!" 
((3,7)) 
 
&lt;/script&gt; 
 
// The result is lo world 
 
// Complex type (Chinese or Chinese-English mixed intercept) 
&lt;script&gt; 
//Intercept the string and include Chinese processing//(string, length, increase...)function subString(str, len, hasDot) 
{ 
 var newLength = 0; 
 var newStr = ""; 
 var chineseRegex = /[^\x00-\xff]/g; 
 var singleChar = ""; 
 var strLength = (chineseRegex,"**").length; 
 for(var i = 0;i &lt; strLength;i++) 
 { 
 singleChar = (i).toString(); 
 if((chineseRegex) != null) 
 { 
  newLength += 2; 
 } 
 else 
 { 
  newLength++; 
 } 
 if(newLength &gt; len) 
 { 
  break; 
 } 
 newStr += singleChar; 
 } 
 
 if(hasDot &amp;&amp; strLength &gt; len) 
 { 
 newStr += "..."; 
 } 
 return newStr; 
} 
 
(subString("Hello, this is a test!",10,1)); // The parameters are string in sequence, the intercepted length and whether to display ellipses&lt;/script&gt; 

15. Split string

&lt;script type="text/javascript"&gt; 
 
var str = 'this_is_a_test_!'; 
var arr = ('_'); 
 
(arr + "&lt;br /&gt;"); // List all(arr[0] + "&lt;br /&gt;"); // Take single item 
&lt;/script&gt;