The most commonly used JS code fragment in front-end development

Is it really difficult to learn and use this programming language skillfully? This article summarizes some of the most commonly used JS code fragments in front-end development, hoping to be helpful and fruitful for your study and work.

HTML 5 DOM selector

javascript code

// querySelector() returns the first matching element
var item = document.querySelector('.item');
console.log(item);

// querySelectorAll() returns all matched elements, a nodeList collection
var items = document.querySelectorAll('.item');
console.log(items[0]);

Block default behavior

javascript code

// Native js
document.getElementById('btn').addEventListener('click', function (event) {
    event = event || window.event;

    if (event.preventDefault){
        // w3c method prevents default behavior
        event.preventDefault();
    } else{
        // ie block default behavior
        event.returnValue = false;
    }
}, false);

// jQuery
$('#btn').on('click', function (event) {
    event.preventDefault();
});

Stop bubbles

javascript code

// Native js
document.getElementById('btn').addEventListener('click', function (event) {
    event = event || window.event;

    if (event.stopPropagation){
        // w3c method to prevent bubbling
        event.stopPropagation();
    } else{
        // ie stops bubbling
        event.cancelBubble = true;
    }
}, false);

// jQuery
$('#btn').on('click', function (event) {
    event.stopPropagation();
});

Mouse wheel events

javascript code

$('#content').on("mousewheel DOMMouseScroll", function (event) { 
    // chrome & ie || // firefox
    var delta = (event.originalEvent.wheelDelta && (event.originalEvent.wheelDelta > 0 ? 1 : -1)) || (event.originalEvent.detail && (event.originalEvent.detail > 0 ? -1 : 1));  

    if (delta > 0) { 
        // scroll up
        console.log('mousewheel top');
    } else if (delta < 0) {
        // Scroll down
        console.log('mousewheel bottom');
    } 
});

Check whether the browser supports svg

javascript code

function isSupportSVG() { 
    var SVG_NS = 'http://www.w3.org/2000/svg';
    return !!document.createElementNS &&!!document.createElementNS(SVG_NS, 'svg').createSVGRect; 
} 

// test
console.log(isSupportSVG());

Check whether the browser supports canvas

javascript code

function isSupportCanvas() {
    if(document.createElement('canvas').getContext){
        return true;
    }else{
        return false;
    }
}

// Test, open Google browser console to view results
console.log(isSupportCanvas());

Check whether it is wechat browser

javascript code

function isWeiXinClient() {
    var ua = navigator.userAgent.toLowerCase(); 
    if (ua.match(/MicroMessenger/i)=="micromessenger") { 
        return true; 
    } else { 
        return false; 
    }
}

// test
alert(isWeiXinClient());

jQuery gets the coordinates of the mouse on the picture

javascript code

$('#myImage').click(function(event){
    //Get the coordinates of the mouse on the picture 
    console.log('X: ' + event.offsetX+'\n Y:' + event.offsetY); 

    //Get the coordinates of the element relative to the page 
    console.log('X: '+$(this).offset().left+'\n Y:'+$(this).offset().top);
});

Verification code countdown code

html code

<!-- dom -->
<input id="send" type="button" value="Send verification code">

javascript code

// Native js version
var times = 60, // Temporarily set to 60 seconds
    timer = null;

document.getElementById('send').onclick = function () {
    // Timing starts
    timer = setInterval(function () {
        times--;

        if (times <= 0) {
            send.value = 'Send verification code';
            clearInterval(timer);
            send.disabled = false;
            times = 60;
        } else {
            send.value = times + 'Seconds after retry';
            send.disabled = true;
        }
    }, 1000);
}

javascript code

// jQuery version
var times = 60,
    timer = null;

$('#send').on('click', function () {
    var $this = $(this);

    // Timing starts
    timer = setInterval(function () {
        times--;

        if (times <= 0) {
            $this.val('Send verification code');
            clearInterval(timer);
            $this.attr('disabled', false);
            times = 60;
        } else {
            $this.val(times + 'Seconds after retry');
            $this.attr('disabled', true);
        }
    }, 1000);
});

Some common regular expressions

javascript code

//Match letters, numbers, Chinese characters 
/^([A-Za-z0-9]|[\u4e00-\u9fa5])*$/ 

//Verify mailbox 
/^\w+@([0-9a-zA-Z]+[.])+[a-z]{2,4}$/ 

//Verify phone number 
/^1[3|5|8|7]\d{9}$/ 

//Verify URL 
/^http:\/\/.+\./

//Verify ID number 
/(^\d{15}$)|(^\d{17}([0-9]|X|x)$)/ 

//Regular expressions matching Chinese characters 
/[\u4e00-\u9fa5]/ 

//Match double byte characters (including Chinese characters) 
/[^\x00-\xff]/

js timestamp, Ms format

javascript code

function formatDate(now) { 
    var y = now.getFullYear();
    var m = now.getMonth() + 1; // Pay attention to adding 1 to the month in js 
    var d = now.getDate();
    var h = now.getHours(); 
    var m = now.getMinutes(); 
    var s = now.getSeconds();

    return y + "-" + m + "-" + d + " " + h + ":" + m + ":" + s; 
} 

var nowDate = new Date(2016, 5, 13, 19, 18, 30, 20);

console.log(nowDate.getTime()); // Get the current number of milliseconds: 1465816710020
console.log(formatDate(nowDate));

js limit the number of characters (Note: 2 characters for one Chinese character)

html code

<input id="txt" type="text">

javascript code

//String truncation
function getByteVal(val, max) {
    var returnValue = '';
    var byteValLen = 0;
    for (var i = 0; i < val.length; i++) {
        if (val[i].match(/[^\x00-\xff]/ig) != null) byteValLen += 2; else byteValLen += 1;
        if (byteValLen > max) break;
        returnValue += val[i];
    }
    return returnValue;
}

$('#txt').on('keyup', function () {
    var val = this.value;
    if (val.replace(/[^\x00-\xff]/g, "**").length > 14) {
        this.value = getByteVal(val, 14);
    }
});

js to determine whether the mobile terminal and browser kernel

javascript code

var browser = { 
    versions: function() { 
        var u = navigator.userAgent; 
        return { 
            trident: u.indexOf('Trident') > -1, //IE kernel 
            presto: u.indexOf('Presto') > -1, //opera kernel 
            webKit: u.indexOf('AppleWebKit') > -1, //Apple, Google kernel 
            gecko: u.indexOf('Firefox') > -1, //Gecko, Firefox kernel 
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //Mobile terminal or not 
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios 
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android 
            iPhone: u.indexOf('iPhone') > -1 , //iPhone 
            iPad: u.indexOf('iPad') > -1, //iPad 
            webApp: u.indexOf('Safari') > -1 //Safari 
        }; 
    }
} 

if (browser.versions.mobile() || browser.versions.ios() || browser.versions.android() || browser.versions.iPhone() || browser.versions.iPad()) { 
    alert('Mobile terminal'); 
}

getBoundingClientRect() get element location

javascript code

//It returns an object, which contains four attributes: left, right, top and bottom
var myDiv = document.getElementById('myDiv');
var x = myDiv.getBoundingClientRect().left; 
var y = myDiv.getBoundingClientRect().top; 

// Equivalent to jquery's: $(this).offset().left, $(this).offset().top // js's: this.offsetLeft, this.offsetTop

HTML5 full screen

javascript code

function fullscreen(element) {
    if (element.requestFullscreen) {
        element.requestFullscreen();
    } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
    } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
    }
}

fullscreen(document.documentElement);

Click: join

Tags: Javascript Mobile JQuery IE

Posted on Sun, 01 Dec 2019 08:52:17 -0800 by mattm591