JavaScript Custom functions

Source: Internet
Author: User
Tags hash setcookie unique id

$()

Well deserved, the most valuable function, can save how much traffic ah. The first to be realized by Prototype.js, the legacy of the prehistoric era of the precious beast, now has many variants:
01.function $ () {
var elements = [];
for (var i = 0; i < arguments.length; i++) {
var element = Arguments[i];
if (typeof element = = ' String ')
element = document.getElementById (element);
if (arguments.length = 1)
return element;
Elements.push (Element);
10.}
One. return elements;
12.}

2, GetStyle () and SetStyle ()

Functions that all UI controls should exist to dynamically set styles and get styles. This can be written very short, but also can be written very long, but to get the exact style, a word: difficult! But I found that a lot of problems are originated in IE, Microsoft's developers do not seem to have ever intended to give getcomputedstyle such a function, and the similar currentstyle will return auto, Inhert, "" and so You laugh and cry the value, This is not yet counted on the difficulty of IE quirks mode! The implementation of all kinds of libraries is very long and difficult to separate out, the following is my implementation of the version:
01.function SetStyle (el,prop,value) {
if (prop = = "opacity" &&!+ "v1") {
The//ie7 bug:filter filter requires Haslayout=true to execute (otherwise no effect)
if (!el.currentstyle | |!el.currentstyle.haslayout) el.style.zoom = 1;
Prop = "Filter";
An. if (!! Window. Xdomainrequest) {
Value = "Progid:DXImageTransform.Microsoft.Alpha (style=0,opacity=" +value*100+ ")";
}else{
Value = "Alpha (opacity=" +value*100+ ")"
10.}
11.}
El.style.cssText + + (prop+ ":" +value);
13.}
function GetStyle (EL, style) {
if (!+ "v1") {
style = Style.replace (/-(w)/g, function (all, letter) {
return Letter.touppercase ();
18.});
return El.currentstyle[style];
}else{
Return Document.defaultView.getComputedStyle (EL, null). GetPropertyValue (Style)
22.}
23.}

About SetStyle can also see me another blog, after all, now set the style is inline style, and HTML mixed together.

3, GetCookie (), Setcookie () and Deletecookie ()

Do BBS and commercial website should often use, there is no reason to let users enter the password every time to log in. We need cookies to implement the automatic login feature:
01.function GetCookie (name) {
var start = document.cookie.indexOf (name + "=");
var len = start + name.length + 1;
if ((!start) && (name!= document.cookie.substring (0, name.length)) {
-Return null;
06.}
The. if (start = = 1) return null;
var end = Document.cookie.indexOf ('; ', Len);
if (end = = 1) end = Document.cookie.length;
Return unescape (document.cookie.substring (len, end));
11.}
12.function Setcookie (name, value, expires, path, domain, secure) {
var today = new Date ();
Today.settime (Today.gettime ());
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
17.}
var expires_date = new Date (Today.gettime () + (expires));
Document.cookie = name+ ' = ' +escape (value) +
((expires)? '; expires= ' +expires_date.togmtstring (): ') +//expires.togmtstring ()
(path)? ';p ath= ' + path: ') +
(domain)? ';d omain= ' + domain: ') +
(secure)? '; secure ': ';
24.}
25.function Deletecookie (name, path, domain) {
-if (GetCookie (name)) Document.cookie = name + ' = ' +
(path)? ';p ath= ' + path: ') +
(domain)? ';d omain= ' + domain: ') +
Expires=thu, 01-jan-1970 00:00:01 GMT ';
30.}

4, InArray ()

Used to determine if a value exists in the check array, the following method is taken from the prototype class library:
1.array.prototype.inarray = function (value) {
2. for (var i=0,l = this.length i <l; i++) {
3. if (this[i] = = value) {
4. return true;
5.}
6.}
7. return false;
8.};

5, InsertAfter ()

DOM provides only insertbefore, and it is necessary for us to implement insertafter ourselves. But I think insertadjacentelement is a better choice, and now it is implemented in addition to other Firefox browsers. Here's the Jeremy Keith version:
1.function InsertAfter (parent, node, Referencenode) {
2. Parent.insertbefore (node, referencenode.nextsibling);
3.}


6, Toggle ()

Used to show or hide a DOM element:
01.function Toggle (obj) {
var el = document.getElementById (obj);
if (El.style.display!= ' None ') {
El.style.display = ' None ';
05.}
/else {
El.style.display = ';
08.}
09.}


7, Cssquery ()

Alias for Getelementsbyseletor, the first implementation by Dean Edwards, Prototype.js, jquery and other class libraries have a corresponding implementation, where jquery integrates it into the $ () selector, reputation over its predecessors. However, IE8, such as the new browser has been implemented Queryselector and Queryselectorall method, until IE6 and IE7 scrapped the day, it is useless. There is no worry in the realization of its principle to explain. Because too long, will not stick out, specific to the original author website to see.

8, Getelementsbyclass ()

I have a collection fetish, with many versions on hand, and finally brainstorming myself to achieve one. Here is my implementation:
01.var getelementsbyclassname = function (Searchclass, Node,tag) {
if (document.getelementsbyclassname) {
Return Document.getelementsbyclassname (Searchclass)
}else{
node = node | | Document
Tag = Tag | | "*";
Modified var classes = Searchclass.split (""),
elements = (Tag = = "*" && node.all)? Node.all:node.getElementsByTagName (TAG),
Patterns = [],
Returnelements = [],
One. Current,
Match;
var i = classes.length;
while (I->= 0) {
Patterns.push (New RegExp ("(^|\s)" + Classes[i] + "(\s|$)");
16.}
var j = elements.length;
while (--j >= 0) {
current = Elements[j];
Match = false;
For (Var k=0, kl=patterns.length k<kl; k++) {
Match = Patterns[k].test (current.classname);
if (!match) break;
24.}
if (match) Returnelements.push (current);
26.}
return returnelements;
28.}
29.}

9, Addloadevent ()

I have discussed this function before, not in detail, is a bit slow, the major class libraries basically ignore it, the implementation of the Domready version. Here is the implementation of Simon Willison:
01.var addloadevent = function (fn) {
var oldonload = window.onload;
if (typeof window.onload!= ' function ') {
Window.onload = fn;
}else {
Window.onload = function () {
Oldonload ();
FN ();
09.}
10.}
11.}

10, Addevent

The most popular version of the internet is Scott Andrew, which is said to have played a game in the JavaScript world (which we can see on page 100th of Pro JavaScript techniques) or browse the PPK Web site to solicit the functions for adding events and removing events. He is the winner. The following is his implementation:
01.function addevent (Elm, Evtype, FN, usecapture) {
02.  if (elm.addeventlistener) {
03.  ;   Elm.addeventlistener (Evtype, FN, usecapture);//dom2.0
04.    return true;
05. }
06.  Else if (elm.attachevent) {
07.    var r = elm.attachevent (' on ' + Evtype, fn);//ie5+ 08.    return R;
09. }
10.  Else {
11.    elm[' on ' + evtype] = fn;//dom 0
12. }
13.}
 

The following is the version of Dean Edwards:
01.function addevent (Elm, Evtype, FN, usecapture) {
if (Elm.addeventlistener) {
Elm.addeventlistener (Evtype, FN, usecapture);//dom2.0
return true;
05.}
An. else if (elm.attachevent) {
Modified var r = elm.attachevent (' on ' + Evtype, fn);//ie5+
"Return R";
09.}
. else {
elm[' on ' + evtype] = fn;//dom 0
12.}
13.}


The following is the version of Dean Edwards:
01.//addevent/removeevent written by Dean Edwards, 2005
02.//with input from Tino Zijdel
03.//http://dean.edwards.name/weblog/2005/10/add-event/
04.function addevent (element, type, handler) {
05.//Assign a unique ID to each event handler function
if (!handler.$ $guid) handler.$ $guid = addevent.guid++;
07.//Create a hash table for the event type of the element
An. if (!element.events) element.events = {};
09.//For each "element/event" to create an event handler for the hash table
var handlers = Element.events[type];
One. if (!handlers) {
Handlers = Element.events[type] = {};
13.//Storage of existing event handler functions (if any)
. if (element["on" + type]) {
Handlers[0] = element["on" + type];
16.}
17.}
18.//Save event handler function in hash table
handlers[handler.$ $guid] = handler;
20.//Assign a global event handler function to do all the work
Element["on" + type] = Handleevent;
22.};
23.//the counter used to create a unique ID
24.addevent.guid = 1;
25.function removeevent (element, type, handler) {
26.//Remove event handler from hash table
if (element.events && Element.events[type]) {
Delete element.events[type][handler.$ $guid];
29.}
30.};
31.function Handleevent (Event) {
var returnvalue = true;
33.//Capture Event object (ie use global event object)
Event = Event | | Fixevent (window.event);
35.//Get the reference of the hash table of the event handler function
var handlers = This.events[event.type];
37.//Perform each processing function
for (var i in handlers) {
this.$ $handleEvent = handlers[i];
if (this.$ $handleEvent (event) = = False) {
ReturnValue = false;
42.}
43.}
ReturnValue return;
45.};
46.//add some "missing" functions to the IE event object
47.function Fixevent (Event) {
48.//Add Standard to the method of the Consortium
Event.preventdefault = Fixevent.preventdefault;
Event.stoppropagation = fixevent.stoppropagation;
A. return event;
52.};
53.fixevent.preventdefault = function () {
This.returnvalue = false;
55.};
56.fixevent.stoppropagation = function () {
This.cancelbubble = true;
58.};

The function is very formidable, solves the IE the this to point to the question, the event always as the first parameter passes in, the cross browser is not to mention.

In addition, I have also treasured a version of the HTML5 workgroup:
01.var addevent= (function () {
if (Document.addeventlistener) {
return function (EL,TYPE,FN) {
An. if (el.length) {
for (Var i=0;i<el.length;i++) {
Addevent (EL[I],TYPE,FN);
07.}
}else{
El.addeventlistener (Type,fn,false);
10.}
11.};
}else{
return function (EL,TYPE,FN) {
if (el.length) {
for (Var i=0;i<el.length;i++) {
Addevent (EL[I],TYPE,FN);
17.}
}else{
El.attachevent (' on ' +type,function () {
Return Fn.call (el,window.event);
21.});
22.}
23.};
24.}
25.}) ();

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.