Using Java scripts

JavaScript is a prototyped-oriented scenario programming language. It is a dialect of the ECMAScript language.

JavaScript is commonly used as an embedded language for programmatic access to application objects. The widest application is found in browsers as a scripting language for giving interactivity to web pages. The main architectural features: dynamic typing, weak typing, automatic memory management, prototyping programming, functions as first-class objects. JavaScript has been influenced by many languages, with the development was the goal to make the language similar to Java, but at the same time easy for use by non-programmers. The JavaScript language is not owned by any company or organization, which distinguishes it from a number of programming languages ​​used in web development. The name "JavaScript" is a registered trademark of Oracle Corporation .

Top 10 JavaScript features

Modern javascript-frameworks, certainly, are able all these functions. But sometimes you need to do something without the framework. For different reasons. For this, this collection of useful functions is intended.

10) addEvent ()

Undoubtedly, the most important tool in event management! Regardless of which version you are using and who it is written, it does what it says in the name: appends an event handler to the element.

  Function addEvent (elem, evType, fn) {
	 If (elem.addEventListener) {
		 Elem.addEventListener (evType, fn, false);
	 }
	 Else if (elem.attachEvent) {
		 Elem.attachEvent ('on' + evType, fn)
	 }
	 Else {
		 Elem ['on' + evType] = fn
	 }
 }

This code has two advantages: it is simple and cross-browser.

Its main drawback is that it does not pass this to the handler for IE. More precisely, it does not do attachEvent.

A simple work around this

To pass the correct this, you can replace the corresponding addEvent line with:

elem.attachEvent("on"+evType, function() { fn.apply(elem) })

This solves the problem with this, but the handler can not be removed in any way. DetachEvent should call exactly the function that was passed to attachEvent.

There are two options for circumventing the problem:

1) Return the function used to assign the handler:

  Function addEvent (elem, evType, fn) {
	 If (elem.addEventListener) {
		 Elem.addEventListener (evType, fn, false)
  Return fn
	 }

  Iefn = function () {fn.call (elem)} 
  Elem.attachEvent ('on' + evType, iefn)
	 Return iefn
 }

 Function removeEvent (elem, evType, fn) {
	 If (elem.addEventListener) {
		 Elem.removeEventListener (evType, fn, false)
  Return
	 }
 
  Elem.detachEvent ('on' + evType, fn)
 } 

It is used like this:

  Function handler () { 
  Alert (this) 
 }
 Var fn = addEvent (elem, "click", handler)
 ...
 RemoveEvent (elem, "click", fn) 

2) You can not use this in the event handler at all, but pass the element through the closure:

  Function addEvent (elem, evType, fn) {
	 If (elem.addEventListener) {
		 Elem.addEventListener (evType, fn, false)
  Return fn
	 }

  Iefn = function () {fn.call (elem)} 
  Elem.attachEvent ('on' + evType, iefn)
	 Return iefn
 }

 Function removeEvent (elem, evType, fn) {
	 If (elem.addEventListener) {
		 Elem.removeEventListener (evType, fn, false)
  Return
	 }
 
  Elem.detachEvent ('on' + evType, fn)
 } 

It is used like this:

  Function handler () { 
  // use not this, but the variable referring to the element
  Alert (elem) 
 }
 ...

9) onReady ()

To initialize the page, the window.onload event was historically used , which fires after the page is fully loaded and all objects on it: counters, images, etc.

The onDOMContentLoaded event is a much better choice in 99% of cases. This event is triggered as soon as the DOM document is ready, before loading the images and other objects that do not affect the document structure.

This is very convenient, because Images can load for a long time, and the onDOMContentLoaded handler can make the necessary changes on the page and initialize the interfaces right there, without waiting for the download of everything.

To add a handler, you can use the following cross-browser code:

  Function bindReady (handler) {

	 Var called = false

	 Function ready () {// (1)
		 If (called) return
		 Called = true
		 Handler ()
	 }

	 If (document.addEventListener) {// (2)
		 Document.addEventListener ("DOMContentLoaded", function () {
			 Ready ()
		 }, False)
	 } Else if (document.attachEvent) {// (3)

		 // (3.1)
		 If (document.documentElement.doScroll && window == window.top) {
			 Function tryScroll () {
				 If (called) return
				 If (! Document.body) return
				 Try {
					 Document.documentElement.doScroll ("left")
					 Ready ()
				 } Catch (e) {
					 SetTimeout (tryScroll, 0)
				 }
			 }
			 TryScroll ()
		 }

		 // (3.2)
		 Document.attachEvent ("onreadystatechange", function () {

			 If (document.readyState === "complete") {
				 Ready ()
			 }
		 })
	 }

	 // (4)
  If (window.addEventListener)
  Window.addEventListener ('load', ready, false)
  Else if (window.attachEvent)
  Window.attachEvent ('onload', ready)
  / * Else // (4.1)
  Window.onload = ready
	 * /
 } 
 ReadyList = []
 Function onReady (handler) {
	 If (! ReadyList.length) {
		 BindReady (function () {
			 For (var i = 0; i <readyList.length; i ++) {
				 ReadyList [i] ()
			 }
		 })
	 }
	 ReadyList.push (handler)
 }

Using:

 OnReady (function () {
  // ...
 })

8) getElementsByClass ()

Initially, it is not written by anyone specifically. Many developers wrote their own versions and the draw did not prove to be better than the rest.

The following function uses the built-in getElementsByClass method, if any, and searches for the items themselves in browsers where this method does not exist.

  If (document.getElementsByClassName) {
 GetElementsByClass = function (classList, node) { 
 Return (node ​​|| document) .getElementsByClassName (classList)
 }
 } Else {
 GetElementsByClass = function (classList, node) {
 Var node = node ||  Document,
 List = node.getElementsByTagName ('*'), 
 Length = list.length, 
 ClassArray = classList.split (/ \ s + /), 
 Classes = classArray.length, 
 Result = [], i, j
 For (i = 0; i <length; i ++) {
 For (j = 0; j <classes; j ++) {
				 If (list [i] .className.search ('\\ b' + classArray [j] + '\\ b')! = -1) {
					 Result.push (list [i])
					 Break
				 }
			 }
		 }
	
		 Return result
	 }
 }

ClassList - A list of classes separated by spaces, the elements to search for.

Node - The context of the search, inside which node to look for

For example:

  Var div = document.getElementById ("mydiv")
 Elements = getElementsByClass ('class1 class2', div) 

7) addClass () / removeClass ()

The following two functions add and remove the element's DOM class.

  Function addClass (o, c) {
  Var re = new RegExp ("(^ | \\ s)" + c + "(\\ s | $)", "g")
  If (re.test (o.className)) return
  O.className = (o.className + "" + c) .replace (/ \ s + / g, "") .replace (/ (^ | $) / g, "")
 }
 
 Function removeClass (o, c) {
  Var re = new RegExp ("(^ | \\ s)" + c + "(\\ s | $)", "g")
  O.className = o.className.replace (re, "$ 1"). Replace (/ \ s + / g, "") .replace (/ (^ | $) / g, "")
 } 

6) toggle ()

To be honest, there are probably more options for this function than it would be necessary.

This option does not in any way claim to be a universal "switch" function, but it performs the basic functionality of showing and hiding.


Function toggle (), folk words

  Function toggle (el) {
  El.style.display = (el.style.display == 'none')?  '': 'None'
 }

Note that there is not a word about display = 'block' in the function, instead the empty value display = '' is used . A blank value means a reset of the property, i.e. The property returns to the value specified in CSS.

Thus, if the value of display for this element, taken from CSS is none (the element is hidden by default), then this toggle function will not work.

This version of the toggle function is beautiful and simple, but this and some other drawbacks make it not universal enough.

5) insertAfter ()

Like getElementsByClass , this function for some reason does not exist in the DOM standard. Perhaps to avoid duplication of functionality, because InsertAfter is implemented only one line.

  Function insertAfter (parent, node, referenceNode) {
  Parent.insertBefore (node, referenceNode.nextSibling);
 }

4) inArray ()

It is unfortunate that this is not part of the built-in functionality of the DOM. But now we have the opportunity to always insert such remarks!

For search, this function uses the === check, which searches for an exact comparison, without casting the types.

The Array.prototype.indexOf method is not supported in all browsers, so it is used if it exists.

  InArray = Array.prototype.indexOf?
  Function (arr, val) {
  Return arr.indexOf (val)! = -1
  }:
  Function (arr, val) {
  Var i = arr.length
  While (i--) {
  If (arr [i] === val) return true
  }
  Return false
  }

3, 2, and 1) getCookie (), setCookie (), deleteCookie ()

In javascript, there is no way to work properly with cookies without additional functions. I do not know who designed the document.cookie , but it's done extremely poorly.

Therefore, the following functions or their analogs are simply necessary.

  // returns cookie if there is or undefined
 Function getCookie (name) {
	 Var matches = document.cookie.match (new RegExp (
	  "(?: ^ |;)" + Name.replace (/([\.$?* | {} \ (\) \ [\] \\\ / \ + ^]) / g, '\\ $ 1' ) + "= ([^;] *)"
	 ))
	 Return matches?  DecodeURIComponent (matches [1]): undefined 
 }

 // sets the cookie
 Function setCookie (name, value, props) {
	 Props = props ||  {}
	 Var exp = props.expires
	 If (typeof exp == "number" && exp) {
		 Var d = new Date ()
		 D.setTime (d.getTime () + exp * 1000)
		 Exp = props.expires = d
	 }
	 If (exp && exp.toUTCString) {props.expires = exp.toUTCString ()}

	 Value = encodeURIComponent (value)
	 Var updatedCookie = name + "=" + value
	 For (var propName in props) {
		 UpdatedCookie + = ";" + propName
		 Var propValue = props [propName]
		 If (propValue! == true) {updatedCookie + = "=" + propValue}
	 }
	 Document.cookie = updatedCookie

 }

 // removes the cookie
 Function deleteCookie (name) {
	 SetCookie (name, null, {expires: -1})
 }

Arguments:

  • Name name of the cookie
  • Value cookie (string)
  • Props Object with additional properties for setting a cookie:
    • Expires Cookie expiration time. Interpreted differently, depending on the type:
      • If the number is the number of seconds before the expiration.
      • If the object of type Date is the exact expiration date.
      • If expires in the past, the cookie will be deleted.
      • If expires is absent or equal to 0, then the cookie will be set as session and will disappear when the browser is closed.
    • Path Path for cookie.
    • Domain A cookie domain.
    • Secure Only send cookies over a secure connection.

Last but often useful: byId

It allows the function to work the same when passing a DOM node or its id.

  Function byId (node) {
  Return typeof node == 'string'?  Document.getElementById (node): node
 }

It is used simply:

  Function hide (node) {
  Node = byId (node)
  Node.style.display = 'none'
 }

 Function animateHide (node)
  Node = byId (node)
  Something (node)
  Hide (node)
 }

Here, both functions are polymorphic, they allow both the node and its id, which is quite convenient, because Allows you not to do unnecessary conversions node <-> id.