JavaScript

[JavaScript]ShopifyCartAPIを叩く(update.js)

let sendData = {
    updates : {}
};
this.deleteItems.forEach((item,index)=>{
    sendData.updates[item.key] = 0;
});
let options = {
    method  : 'POST',
    credentials: 'same-origin',
    headers : {
        'Content-Type': 'application/json'
    },
    body    : JSON.stringify(sendData)
};
fetch(window.Shopify.routes.root+'cart/update.js',options)
.then((response)=>{
    if (!response.ok) {
        throw new Error();
    }
    return response.json;
})
.then((json)=>{
    this.finishFetch(2);
})
.catch((error)=>{
    console.log(error);
});

[JavaScript]ShopifyCartAPIを叩く(change.js)

let sendData = {
    id         : item.key,
    quantity   : item.quantity,
    properties : {}
};
item.properties.forEach((property,index)=>{
    sendData.properties['プロパティ'+(index+1)] = property.value;
});
let options = {
    method       : 'POST',
    credentials  : 'same-origin',
    headers : {
        'Content-Type' : 'application/json'
    },
    body         : JSON.stringify(sendData)
};
fetch(window.Shopify.routes.root+'cart/change.js',options)
.then((response)=>{
    if (!response.ok) {
        throw new Error();
    }
    return response.json;
})
.then((json)=>{
    this.finishFetch();
})
.catch((error)=>{
    console.log(error);
});

[Shopify][JavaScript]住所編集の国で都道府県更新

Liquid(HTML)

国<select name="address[country]" {% if form.country != blank %}data-default-label="{{ form.country }}{% else %}data-default="Japan{% endif %}">{{ country_option_tags }}</select><br>
都道府県<select name="address[province]" data-default-label="{{ form.province }}"></select>

JavaScript

document.querySelectorAll('[name="address[country]"]').forEach((elm,index)=>{
    elm.addEventListener('change',(e)=>{
        onChangeCountry(e);
    });
});
onChangeCountry(e){
    const option = e.target.querySelector('[value="'+e.target.value+'"]');
    const provinceSelect = e.target.form.querySelector('[name="address[province]"]');
    if(option && provinceSelect){
        let options = [];
        const provinces = JSON.parse(option.dataset['provinces']);
        provinces.forEach((province,index)=>{
            options.push('<option value="'+province[0]+'">'+province[1]+'</option>');
        });
        provinceSelect.innerHTML = options.join('');
    }
}

[JavaScript]ファイルサイズ取得

const options = {
   method  : "HEAD"
};
fetch(elm.href,options)
    .then((response)=>{
        if (!response.ok) {
            throw new Error();
        }
        return response;
    })
    .then((response)=>{
        const fileSize = response.headers.get("Content-Length");
        if(fileSize) {
            console.log(fileSize);
        }else{
            throw new Error();
        }
    })
    .catch((error)=>{
    });

[JavaScript]getRGBAByHex

getRGBAByHex(hex,alpha){
    if (hex.slice(0,1) == "#")hex = hex.slice(1) ;
    if (hex.length == 3)hex = hex.slice(0,1) + hex.slice(0,1) + hex.slice(1,2) + hex.slice(1,2) + hex.slice(2,3) + hex.slice(2,3);
    let rgb = [hex.slice(0,2),hex.slice(2,4),hex.slice(4,6)].map(function(str){
        return parseInt(str,16);
    });
    return `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${alpha})`;
}

[JavaScript]canvas.clip

animate() {
    requestAnimationFrame(()=>{
        this.animate();
    });
    const ctx;
    ctx = canvas.getContext('2d');
    ctx.globalCompositeOperation = "source-over";
    ctx.globalAlpha = 1.0;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.beginPath();
    ctx.rect(0,0,canvas.width,100);
    ctx.clip();
    //ここに描画処理
    ctx.restore();
}

[JavaScript]スクロール無効化

window.addEventListener('touchmove', (e)=>{this.cancelScroll(e);}, { passive: false });
window.addEventListener('mousewheel', (e)=>{this.cancelScroll(e);}, { passive: false });

cancelScroll(e) {
    e.preventDefault();
}

[JavaScript]getDateStrByFormat

getDateStrByFormat(format,d,defaultValue){
    if(typeof d == 'string'){
        d = this.getDateByYYYYMMDD(d);
    }
    if(!d){
        if(defaultValue != undefined && defaultValue != null){
            return defaultValue;
        }else{
            d = new Date();
        }
    }
    if(!format){
        format = 'Y-m-d';
    }
    const _pz = function(v,digits){
        var vs = v.toString();
        while(vs.length < digits){
            vs = '0' + vs;
        }
        return vs;
    };
    return format
        .replace(/Y/g,d.getFullYear())
        .replace(/y/g,d.getFullYear().toString().substr(2,2))
        .replace(/n/g,d.getMonth()+1)
        .replace(/m/g,_pz(d.getMonth()+1,2))
        .replace(/j/g,d.getDate())
        .replace(/d/g,_pz(d.getDate(),2))
        .replace(/G/g,d.getHours())
        .replace(/H/g,_pz(d.getHours(),2))
        .replace(/i/g,_pz(d.getMinutes(),2))
        .replace(/s/g,_pz(d.getSeconds(),2))
        .replace(/J/g,['日','月','火','水','木','金','土'][d.getDay()])
        .replace(/D/g,['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][d.getDay()]);
}

[JavaScript]文字列yyyy-mm-ddからDateを得る

js

function getDateByYYYYMMDD(yyyymmdd) {
    var tmp = void 0,
        match = void 0;
    if (match = yyyymmdd.match(/[\d]{4}\-[\d]{2}\-[\d]{2}/)) {
        if (match.length) {
            tmp = match[0].split('-');
        }
    } else if (match = yyyymmdd.match(/[\d]{4}[\d]{2}[\d]{2}/)) {
        if (match.length) {
            tmp = [match[0].substr(0, 4), match[0].substr(4, 2), match[0].substr(6, 2)];
        }
    }
    if (!tmp || tmp.length < 3) {
        return null;
    }
    return new Date(Number(tmp[0]), Number(tmp[1]) - 1, Number(tmp[2]), 0, 0, 0, 0);
}

es6

getDateByYYYYMMDD(yyyymmdd){
    let tmp,match;
    if(match = yyyymmdd.match(/[\d]{4}\-[\d]{2}\-[\d]{2}/)){
        if(match.length){
            tmp = match[0].split('-');
        }
    }else if(match = yyyymmdd.match(/[\d]{4}[\d]{2}[\d]{2}/)){
        if(match.length){
            tmp = [match[0].substr(0,4),match[0].substr(4,2),match[0].substr(6,2)];
        }
    }
    if(!tmp || tmp.length < 3){
        return null;
    }
    return new Date(Number(tmp[0]),Number(tmp[1])-1,Number(tmp[2]),0,0,0,0);
}