вторник, 29 июля 2014 г.

Безопасное создание объектов функцией конструктором без new и с new

// Scope safe constructors

function Person(name, age, job){
    if (this instanceof Person){
        this.name = name;
        this.age = age;
        this.job = job;
    } else {
        return new Person(name, age, job);
    }
}

var person1 = Person('Nicholas', 29, 'Software Engineer');
alert(window.name); // ''
alert(person1.name); // 'Nicholas'
var person2 = new Person('Shelby', 34, 'Ergonomist');
alert(person2.name); // 'Shelby'

Вывод лога console.log() прямо на страницу

function log(message){
    var console = document.getElementById("debuginfo");
    if (console === null){
        console = document.createElement("div");
        console.id = "debuginfo";
        console.style.background = "#dedede";
        console.style.border = "1px solid silver";
        console.style.padding = "5px";
        console.style.width = "400px";
        console.style.position = "absolute";
        console.style.right = "0px";
        console.style.top = "0px";
        document.body.appendChild(console);
    }
    console.innerHTML += "<p>" + message + "</p>";
}

Сериализация всех полей формы

function serialize(form){
    var parts = [],
         field = null,
        i,
        len,
        j,
        optLen,
        option,
        optValue;
    for (i=0, len=form.elements.length; i < len; i++){
        field = form.elements[i];
        switch(field.type){
            case "select-one":
            case "select-multiple":
                                            if (field.name.length){
                                                for (j=0, optLen = field.options.length; j < optLen; j++){
                                                    option = field.options[j];
                                                    if (option.selected){
                                                        optValue = "";
                                                        if (option.hasAttribute){
                                                            optValue = (option.hasAttribute("value") ? option.value : option.text);
                                                       } else {
                                                            optValue = (option.attributes["value"].specified ? option.value : option.text);
                                                        }
                                                        parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(optValue));
                                                    }
                                                }
                                            }
                                            break;
            case undefined: //fieldset
            case "file": //file input
            case "submit": //submit button
            case "reset": //reset button
            case "button": //custom button
                                break;
            case "radio": //radio button
            case "checkbox": //checkbox
                                    if (!field.checked){
                                        break;
                                    }
            /* falls through */
            default:
                       //don’t include form fields without names
                        if (field.name.length){
                            parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value));
                        }
        }
    }
    return parts.join("&");
}

Перемещение по дереву DOM, создание и удаление тэгов и атрибутов

parentNode
childNodes
previousSibling
nextSibling
children
firstChild
lastChild

querySelector
querySelectorAll

appendChild
insertBefore(newNode, beforeNode)
replaceChild(newNode, oldNode)
removeNode
cloneNode(true)

getElementById
getElementsByTagName
getElementsByName - для радиокнопок
getElementsByClassName("username current");

getAttribute
setAttribute
removeAttribute

Also note that, according to HTML5, custom attributes should be prepended with "data-" in order to validate.

createElement
createTextNode
createComment
createDocumentFragment

element.normalize
textNode.splitText

среда, 16 июля 2014 г.

Удаление класса из тэга

<div class=”bd user disabled”>...</div>

removeClassFrom(document.getElementsByTagName()[0], 'user');

function removeClassFrom (element, nameOfTheClassToRemove) {
    var classNames = elementv.className.split(/\s+/)
       , position = -1
       , i
       , len;
     for (i = 0, len = classNames.length; i < len; i++){
        if (classNames[i] === nameOfTheClassToRemove){
            position = i;
            break;
        }
     }
     classNames.splice(position,1);
     element.className = classNames.join(' ');
}

Динамическая загрузка и вставка на страницу CSS стилей

Динамическая загрузка CSS стилей.

function loadStyles (url) {
    var link = document.createElement('link');
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.href = url;
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(link);
}

loadStyles('http://www.mysite.com/styles.css');

Динамическая вставка на страницу CSS стилей.

function loadStyleString (css) {
    var style = document.createElement('style');
    style.type = 'text/css';
    try {
        style.appendChild(document.createTextNode(css));
    } catch (error) {
        style.styleSheet.cssText = css; // Для Internet Explorer
    }
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(style);
}

loadStyleString('body{background-color:red}');

Динамическая загрузка и вставка на страницу JavaScript сценариев

Динамическая загрузка JavaScript сценария.

function loadScript (url) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    document.body.appendChild(script);
}

loadScript('http://www.mysite.com/client.js');

Динамическая вставка на страницу JavaScript сценария.

function loadScriptString (code) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    try {
        script.appendChild(document.createTextNode(code));
    } catch (error){
        script.text = code; // Для Internet Explorer
    }
    document.body.appendChild(script);
}

loadScriptString('function sayHi(){alert("hi");}');