Generic javascript functions
Rus
Eng
Типовые функции javascript

All English-language materials have been translated fully automatically using the Google service

In every project there is a need to check the data in javascript. Most often I use the following checks

Url check

  if (/ ^ (http | https | ftp): \ / \ / [a-z0-9] + ([\ - \.] {1} [a-z0-9] +) * \. [az] {2,5} (: [0-9] {1,5})? (\ /.*)? $ / i.test ($ ("# url"). val ())) {
    console.log ("valid URL");
} else {
    console.log ("invalid URL");
}  

Email verification

  var reg_email = /^^^^^^^^^^^^^^ UsingâzA-Z0-9_\.-.....2,45 * \. [a-zA- Z] {2.20} $ /;

if (reg_email.test (YOUR_VALUE)) {
// Check passed
}  

Checking a mobile phone in international format

  var reg_phone = / ^ (\ s *)? (\ +)? ([- _ (): = +]? \ d [- _ (): = +]?) {10,14 } (\ s *)? $ /;

if (reg_phone.test (YOUR_VALUE)) {
// Check passed
}  

Verifying credit card number

  var cc = / [0-9] {4} {0,1} [0-9] {4} {0,1} [0-9] {4} {0,1} [ 0-9] {4} /;

if (cc.test (YOUR_VALUE)) {
// Check passed
}  

Check credit card date

  var cdate = /^\d {2} {./- }\d {2} }$/;

if (cdate.test (YOUR_VALUE)) {
// Check passed
}  

Credit card cvc verification

  var cvc = / ^ [0-9] {3,4} $ /;

if (cvc.test (YOUR_VALUE)) {
// Check passed
}  

Check for existence

  var isset = function (variable) {
    return typeof (variable)! == "undefined" && variable! == null && variable! == '';
}  

Checking for Json

  function isJson (str) {
    try {
        JSON.parse (str);
    } catch (e) {
        return false;
    }
    return true;
}  

Checking the existence of an element with a class

  if (document.querySelector ('. mydivclass')! == null) {
    // Element found
}  

Checking if an element is in an array

  var blockedTile = new Array ("118", "67", "190", "43", "135", "520");
if (blockedTile.indexOf ("118")! = -1)
{
   // Element found
}  

Tests for touch devices

  function is_touch_device () {
try {
document.createEvent ("TouchEvent");
return true;
} catch (e) {
return false;
}
}

function is_touch_device () {
  return 'ontouchstart' in window;
}

function is_touch_device () {
  return 'ontouchstart' in window // works on most browsers
      || 'onmsgesturechange' in window; // works on IE10 with some false positives
};

function is_touch_device () {
  return 'ontouchstart' in window // works on most browsers
      || navigator.maxTouchPoints; // works on IE10 / 11 and Surface
};

function is_touch_device () {
  var prefixes = '-webkit- -moz- -o- -ms-' .split ('');
  var mq = function (query) {
    return window.matchMedia (query) .matches;
  }

  if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
    return true;
  }

  var query = ['(', prefixes.join ('touch-enabled), ('), 'heartz', ')']. join ('');
  return mq (query);
}
function isMobile () {
var a = navigator.userAgent;
if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge | maemo | midp | mmp | mobile. + firefox | netfront | opera m (ob | in) i | palm (os)? | phone | p (ixi | re) \ / | plucker | pocket | psp | series (4 | 6) 0 | symbian | treo | up \. (Browser | link) | vodafone | wap | windows ce | xda | xiino / i.test (a) || / 1207 | 6310 | 6590 | 3gso | 4thp | 50 [1-6 ] i | 770s | 802s | a wa | abac | ac (er | oo | s \ -) ​​| ai (ko | rn) | al (av | ca | co) | amoi | an (ex | ny | yw) | aptu | ar (ch | go) | as (te | us) | attw | au (di | \ -m | r | s) | avan | be (ck | ll | nq) | bi (lb | rd) | bl (ac | az) | br (e | v) w | bumb | bw \ - (n | u) | c55 \ / | capi | ccwa | cdm \ - | cell | chtm | cldc | cmd \ - | co (mp | nd) | craw | da (it | ll | ng) | dbte | dc \ -s | devi | dica | dmob | do (c | p) o | ds (12 | \ -d) | el (49 | ai ) | em (l2 | ul) | er (ic | k0) | esl8 | ez ([4-7] 0 | os | wa | ze) | fetc | fly (\ - | _) | g1 u | g560 | gene | gf \ -5 | g \ -mo | go (\. w | od) | gr (ad | un) | haie | hcit | hd \ - (m | p | t) | hei \ - | hi (pt | ta) | hp (i | ip) | hs \ -c | ht (c (\ - | | _ | a | g | p | s | t) | tp) | hu (aw | tc) | i \ - ( 20 | go | ma) | i230 | iac (| \ - | \ /) | ibro | idea | ig01 | ikom | im1k | inno | ipaq | iris | ja (t | v) a | jbro | jemu | jigs | kddi | keji | kgt (| \ /) | klon | kpt | kwc \ - | kyo (c | k) | le (no | xi) | lg (g | \ / (k | l | u) | 50 | 54 | \ - [aw]) | libw | lynx | m1 \ -w | m3ga | m50 \ / | ma (te | ui | xo) | mc (01 | 21 | ca) | m \ -cr | me (rc | ri) | mi (o8 | oa | ts) | mmef | mo (01 | 02 | bi | de | do | t (\ - | | o | v) | zz) | mt (50 | p1 | v) | mwbp | mywa | n10 [0-2] | n20 [2-3] | n30 (0 | 2) | n50 (0 | 2 | 5 ) | n7 (0 (0 | 1) | 10) | ne ((c | m) \ - | on | tf | wf | wg | wt) | nok (6 | i) | nzph | o2im | op (ti | wv) | oran | owg1 | p800 | pan (a | d | t) | pdxg | pg (13 | \ - ([1-8] | c)) | phil | pire | pl (ay | uc) | pn \ -2 | po (ck | rt | se) | prox | psio | pt \ -g | qa \ -a | qc (07 | 12 | 21 | 32 | 60 | \ - [2-7] | i \ -) | qtek | r380 | r600 | raks | rim9 | ro (ve | zo) | s55 \ / | sa (ge | ma | mm | ms | ny | va) | sc (01 | h \ - | oo | p \ - ) | sdk \ / | se (c (\ - | 0 | 1) | 47 | mc | nd | ri) | sgh \ - | shar | sie (\ - | m) | sk \ -0 | sl (45 | id) | sm (al | ar | b3 | it | t5) | so (ft | ny) | sp (01 | h \ - | v \ - | v) | sy (01 | mb) | t2 (18 | 50 ) | t6 (00 | 10 | 18) | ta (gt | lk) | tcl \ - | tdg \ - | tel (i | m) | tim \ - | t \ -mo | to (pl | sh) | ts (70 | m \ - | m3 | m5) | tx \ -9 | up (\. B | g1 | si) | utst | v400 | v750 | veri | vi (rg | te) | vk (40 | 5 [0 -3] | \ -v) | vm40 | voda | vulc | vx (52 | 53 | 60 | 61 | 70 | 80 | 81 | 83 | 85 | 98) | w3c (\ - |) | webc | whit | wi (g | nc | nw) | wmlb | wonu | x700 | yas \ - | your | zeto | zte \ - / i.test (a.substr (0, 4))) {
return true;
} else {
return false;
}
}
 

Screen resolution check

  if (window.matchMedia ("(max-width: 768px)"))
{
// Check passed
}  

Check file for existence within one domain

  function fileExists (url) {
    if (url) {
        var req = new XMLHttpRequest ();
        req.open ('GET', url, false);
        req.send ();
        return req.status == 200;
    } else {
        return false;
    }
}  

Check if the page is inside an iframe

  var isFramed = false;
try {
isFramed = window! = window.top || document! = top.document || self.location! = top.location;
} catch (e) {
isFramed = true;
}
if (isFramed) {
alert ('The page is loaded in an iframe');
} else {
alert ('The page is loaded not in the iframe');
}  

Trim the line

  console.log ("13:45 PM" .split ('') [0]); // Split by space, take first part
console.log ("13:45 PM" .match (/ \ d? \ d: \ d \ d /) [0]); // match by regular expression
console.log ("13:45 PM" .substr (0, 5)); // 5 characters starting from 0
console.log ("13:45 PM" .substring (0, 5)); // copy by indices [0: 5)
console.log ("13:45 PM" .replace (/ \ s. * /, '')); // replace the space and everything else with an empty string
console.log ("13:45 PM" .slice (0, -3)); // slice without the last three characters  

ToggleClass in javascript native

  function toggleClass (element, className) {
    if (! element ||! className) {
        return;
    }

    var classString = element.className, nameIndex = classString.indexOf (className);
    if (nameIndex == -1) {
        classString + = '' + className;
    }
    else {
        classString = classString.substr (0, nameIndex) + classString.substr (nameIndex + className.length);
    }
    element.className = classString;
}  

Determine that the element is visible. Taken from here

  // Get the desired element
var element = document.querySelector ('# target');

var Visible = function (target) {
  // All positions of the element
  var targetPosition = {
      top: window.pageYOffset + target.getBoundingClientRect (). top,
      left: window.pageXOffset + target.getBoundingClientRect (). left,
      right: window.pageXOffset + target.getBoundingClientRect (). right,
      bottom: window.pageYOffset + target.getBoundingClientRect (). bottom
    },
    // Get the position of the window
    windowPosition = {
      top: window.pageYOffset,
      left: window.pageXOffset,
      right: window.pageXOffset + document.documentElement.clientWidth,
      bottom: window.pageYOffset + document.documentElement.clientHeight
    };

  if (targetPosition.bottom> windowPosition.top && // If the position of the bottom of the element is greater than the position of the top of the window, then the element is visible from above
    targetPosition.top  windowPosition.left && // If the position of the right side of the element is greater than the position of the left side of the window, then the element is visible to the left
    targetPosition.left  

Check if the element is fully visible. Taken from from here

  function is_fully_shown (target) {
var wt = $ (window) .scrollTop ();
var wh = $ (window) .height ();
var eh = $ (target) .height ();
var et = $ (target) .offset (). top;
 
if (et> = wt && et + eh <= wh + wt) {
return true;
} else {
return false;
}
}
 
if (is_fully_shown ('. active')) {
console.log (true);
}  

Add all input values ​​to the array

  var phones = [];
$ ('. aOffer'). each (function () {
if ($ (this) .val ()! == '') {
phones.push ($ (this) .val ());
}
});  

Scroll to top on javascript

  window.scrollTo ({
top: document.getElementById ('payments'). getBoundingClientRect (). top + pageYOffset,
behavior: "smooth"
});  

Javascript number_format php function analog - from here

  function number_format (number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + bugfix by: Michael White (http://getsprink.com)
    // + bugfix by: Benjamin Lupton
    // + bugfix by: Allan Jensen (http://www.winternet.no)
    // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // + bugfix by: Howard Yeend
    // + revised by: Luke Smith (http://lucassmith.name)
    // + bugfix by: Diogo Resende
    // + bugfix by: Rival
    // + input by: Kheang Hok Chin (http://www.distantia.ca/)
    // + improved by: davook
    // + improved by: Brett Zamir (http://brett-zamir.me)
    // + input by: Jay Klehr
    // + improved by: Brett Zamir (http://brett-zamir.me)
    // + input by: Amir Habibi (http://www.residence-mixte.com/)
    // + bugfix by: Brett Zamir (http://brett-zamir.me)
    // + improved by: Theriault
    // + improved by: Drew Noakes
    // * example 1: number_format (1234.56);
    // * returns 1: '1,235'
    // * example 2: number_format (1234.56, 2, ',', '');
    // * returns 2: '1 234.56'
    // * example 3: number_format (1234.5678, 2, '.', '');
    // * returns 3: '1234.57'
    // * example 4: number_format (67, 2, ',', '.');
    // * returns 4: '67, 00 '
    // * example 5: number_format (1000);
    // * returns 5: '1,000'
    // * example 6: number_format (67.311, 2);
    // * returns 6: '67 .31 '
    // * example 7: number_format (1000.55, 1);
    // * returns 7: '1,000.6'
    // * example 8: number_format (67000, 5, ',', '.');
    // * returns 8: '67 .000,00000 '
    // * example 9: number_format (0.9, 0);
    // * returns 9: '1'
    // * example 10: number_format ('1.20', 2);
    // * returns 10: '1.20'
    // * example 11: number_format ('1.20', 4);
    // * returns 11: '1.2000'
    // * example 12: number_format ('1.2000', 3);
    // * returns 12: '1.200'
    var n =! isFinite (+ number)? 0: + number,
        prec =! isFinite (+ decimals)? 0: Math.abs (decimals),
        sep = (typeof thousands_sep === 'undefined')? ',': thousands_sep,
        dec = (typeof dec_point === 'undefined')? '.' : dec_point,
        toFixedFix = function (n, prec) {
            // Fix for IE parseFloat (0.55) .toFixed (0) = 0;
            var k = Math.pow (10, prec);
            return Math.round (n * k) / k;
        },
        s = (prec? toFixedFix (n, prec): Math.round (n)). toString (). split ('.');
    if (s [0] .length> 3) {
        s [0] = s [0] .replace (/ \ B (? = (?: \ d {3}) + (?! \ d)) / g, sep);
    }
    if ((s [1] || '') .length ' + (actual === expected? 'Passed': 'FAILED') + ', got "' + actual + '", expected "' + expected + '".');
    exampleNumber ++;
}

test ('1,235', 1234.56);
test ('1 234.56', 1234.56, 2, ',', '');
test ('1234.57', 1234.5678, 2, '.', '');
test ('67, 00 ', 67, 2,', ','. ');
test ('1,000', 1000);
test ('67 .31 ', 67.311, 2);
test ('1,000.6', 1000.55, 1);
test ('67 .000,00000 ', 67000, 5,', ','. ');
test ('1', 0.9, 0);
test ('1.20', '1.20', 2);
test ('1.2000', '1.20', 4);
test ('1.200', '1.2000', 3);  

Tooltips with HTML code

You can use an unlimited number of hints, hints are well displayed in both desktop and mobile versions. Written in pure javascript and reasonably fast.

jQuery analogs of the FadeIn and FadeIn functions to javascript

  function fadeIn (el) {
    let opacity = 0.01,
        fadeEl = document.querySelector (el);

    if (fadeEl && isHidden (fadeEl)) {
        fadeEl.style.opacity = opacity;
        fadeEl.style.display = "block";
        var timer = setInterval (function () {
            if (opacity> = 1) {
                clearInterval (timer);
            }
            fadeEl.style.opacity = opacity;
            opacity + = opacity * 0.1;
        }, ten);
    }
}

function fadeOut (el) {
    let opacity = 1,
        fadeOutEl = document.querySelector (el);

    if (fadeOutEl) {
        fadeOutEl.style.display = "block";

        var timer = setInterval (function () {
            if (opacity <= 0.01) {
                clearInterval (timer);
                fadeOutEl.style.display = "none";
            }
            fadeOutEl.style.opacity = opacity;
            opacity - = opacity * 0.1;
        }, ten);
    }
}

function isHidden (el) {
    return (el.offsetParent === null)
}  

remove () to javascript

  HTMLElement.prototype.remove = function () {this.parentNode.removeChild (this); return this; }  

Javascript scrollToTop function

var scrollToTop = window.setInterval(function() {
    var pos = window.pageYOffset;
    if ( pos > 0 ) {
        window.scrollTo( 0, pos - 20 ); // how far to scroll on each step
    } else {
        window.clearInterval( scrollToTop );
    }
}, 10); // how fast to scroll (this equals roughly 60 fps)

Comments

There are no comments yet, you can be the first to leave it

Leave a comment

The site uses a comment pre-moderation system, so your message will be published only after approval by the moderator

You are replying to a user's comment

Send

FEEDBACK

Email me

Are you developing a new service, making improvements to the existing one and want to be better than your competitors? You have come to the right place. I offer you a comprehensive studio-level website development. From me you can order design, layout, programming, development of non-traditional functionality, implementation of communication between CMS, CRM and Data Analitics, as well as everything else related to sites, except for promotion.

Contact, I will always advise on all questions and help you find the most effective solution for your business. I am engaged in the creation of sites in Novosibirsk and in other regions of Russia, I also work with the CIS countries. You will be satisfied with our cooperation

An error occurred while sending, please try again after a while
Message sent successfully

Phones

+7(993) 007-18-96

Email

info@tichiy.ru

Address

Россия, г. Москва

By submitting the form, you automatically confirm that you have read and accept the Privacy Policy site

Contact with me
Send message
By submitting the form, you automatically confirm that you have read and accept Privacy policy of site
Sending successful!
Thank you for contacting :) I will contact you as soon as possible
Sending failed
An error occurred while sending the request. Please wait and try again after a while or call my phone number