« Newer Snippets
Older Snippets »
11 total  XML / RSS feed 

DOM output stream class

Simulating an output stream in Javascript

Pass the id of a DOM element to the constructor to get started. Call the clear() method first, if necessary. Then call the write() method as many times as needed. Finally, always remember to call flush() to force your output to appear.
// A little class for outputting HTML into a DOM element
function DOMStream(id) {
    this.elt = document.getElementById(id);
    this.buffer = [];
}
DOMStream.prototype.clear = function() { this.elt.innerHTML = ""; };
DOMStream.prototype.write = function() {
    for(var i = 0; i < arguments.length; i++) this.buffer.push(arguments[i]);
};
DOMStream.prototype.flush = function() {
    this.elt.innerHTML += this.buffer.join("");
    this.buffer.length = 0;
};

If it is not obvious, an important point of this class it to avoid inefficient repeated string concatenation. This is why it uses an array as a buffer, and why the write() method accepts multiple arguments--so you don't have to concatenate them yourself.
var out = new DOMStream("placeholder");
out.write('

', section_title, '

'); outputTable(out, data); // Function defined elsewhere out.flush();

Making Javascript DOM a Piece of Cake with the graft() Function

graft() allows us to build chunks of DOM documents using really simple object notation. Graft() will feel very familiar to anyone who makes extensive use of the JSON format.

I’ll dive right into an example here and show graft in its simplest use. Suppose we have a DOM element somewhere in our document that we want to insert stuff into:

<div id="mycontentdiv">div>


If we wanted to insert a button into the above div element, we could use standard DOM in the following manner:

var mydiv = document.getElementById("mycontentdiv");
var btn = document.createElement("input");
btn.type = "button";
btn.value = "click me";
btn.onclick = function(){this.value="i have been clicked!";};
mydiv.appendChild(btn);


The above button example becomes the following using graft():

graft(
    document.getElementById("mycontentdiv"),
    ["input",
        {
            value:'click me',
            type:'button',
            onclick:'this.value="i have been clicked!";'
        }
    ]
);


// graft() function
// Originally by Sean M. Burke from interglacial.com
// Closure support added by Maciek Adwent

function graft (parent, t, doc) {

    // Usage: graft( somenode, [ "I like ", ['em',
    //               { 'class':"stuff" },"stuff"], " oboy!"] )

    doc = (doc || parent.ownerDocument || document);
    var e;

    if(t == undefined) {
        throw complaining( "Can't graft an undefined value");
    } else if(t.constructor == String) {
        e = doc.createTextNode( t );
    } else if(t.length == 0) {
        e = doc.createElement( "span" );
        e.setAttribute( "class", "fromEmptyLOL" );
    } else {
        for(var i = 0; i < t.length; i++) {
            if( i == 0 && t[i].constructor == String ) {
                var snared;
                snared = t[i].match( /^([a-z][a-z0-9]*)\.([^\s\.]+)$/i );
                if( snared ) {
                    e = doc.createElement(   snared[1] );
                    e.setAttribute( 'class', snared[2] );
                    continue;
                }
                snared = t[i].match( /^([a-z][a-z0-9]*)$/i );
                if( snared ) {
                    e = doc.createElement( snared[1] );  // but no class
                    continue;
                }

                // Otherwise:
                e = doc.createElement( "span" );
                e.setAttribute( "class", "namelessFromLOL" );
            }

            if( t[i] == undefined ) {
                throw complaining("Can't graft an undefined value in a list!");
            } else if(  t[i].constructor == String ||
                                    t[i].constructor == Array ) {
                graft( e, t[i], doc );
            } else if(  t[i].constructor == Number ) {
                graft( e, t[i].toString(), doc );
            } else if(  t[i].constructor == Object ) {
                // hash's properties => element's attributes
                for(var k in t[i]) {
                    // support for attaching closures to DOM objects
                    if(typeof(t[i][k])=='function'){
                        e[k] = t[i][k];
                    } else {
                        e.setAttribute( k, t[i][k] );
                    }
                }
            } else {
                throw complaining( "Object " + t[i] +
                    " is inscrutable as an graft arglet." );
            }
        }
    }

    parent.appendChild( e );
    return e; // return the topmost created node
}

function complaining (s) { alert(s); return new Error(s); }

Toggle Layers across browsers

// description of your code here

function toggleLayer(whichLayer) 
{
        if (document.getElementById) 
        {
                // this is the way the standards work
                var style2 = document.getElementById(whichLayer).style;
                style2.display = style2.display? "":"none";
        }
        else if (document.all)
        {
                // this is the way old msie versions work
                var style2 = document.all[whichLayer].style;
                style2.display = style2.display? "":"none";
        }
        else if (document.layers)
        {
                // this is the way nn4 works
                var style2 = document.layers[whichLayer].style;
                style2.display = style2.display? "":"none";
        }
}


Find All Elements By Class

// Javascript function that will return an array of elements based on DOM element, tag, and class name.
// For instance, getElementsByClassName(document, 'tr', 'INFO') will get all "tr" tags under the document node with the "INFO" class and return an array of them.

function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
            var arrReturnElements = new Array();
            strClassName = strClassName.replace(/\-/g, "\\-");
            var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
            var oElement;
            for(var i=0; i<arrElements.length; i++){
                oElement = arrElements[i];
                if(oRegExp.test(oElement.className)){
                    arrReturnElements.push(oElement);
                }
            }
            return (arrReturnElements)
        }

Update Title

// simple function to update a page's title

updateTitle: function(title) { document.title = title; }

Get HTML

// a stupid function that gets a node's HTML, including the node itself

getHTML: function(node) {
  var div = document.createElement('DIV');
  div.appendChild(node.cloneNode(true));
  return div.innerHTML;
}

childOfID

// moves upward in the tree until an ID or class name is found, returns element

childOfID: function(element, id, isClass) {
  element = $(element);
  do {
    if (isClass && element.hasClassName(id)) return element; 
    if (!isClass && element.id == id) return element;
  } while (element = $(element.parentNode));
  return false;
}

Attach Elements

// takes this.el and copies it to this.elements, replacing CSS selector with DOM object(s)

attachElement: function(p) {
  this.el[p] = $$(this.elements[p]);
  if (this.el[p].length == 1) this.el[p] = this.el[p][0];
},
attachElements: function() {
  this.el = {};
  for (x in this.elements) this.attachElement(x);
},
clearElements: function() {
  for (x in this.el) this.el[x] = null;
}

Смена класса элемента

function change(id, newClass) {
     identity=document.getElementById(id);
     identity.className=newClass;
}

ActiveRecord DOM IDs

The solution—or at least a nice, cheap bandaid that can be applied easily, consists of adding a method to ActiveRecord::Base to help generate these ids without any brainpower involved.

Here’s a very simple implementation that I use in my projects, courtesy of Jamis Buck:



class ActiveRecord::Base
  def dom_id(prefix=nil)
    display_id = new_record? ? "new" : id
    prefix ||= self.class.name.underscore
    prefix != :bare ? "#{prefix.to_s.dasherize}-#{display_id}" : display_id
  end
endSo, you can do stuff like this in your views:

<ul>
<% @entries.each do |entry| %>
  
  • > <%= entry.body %>
  • <% end %> And stuff like this in your controller: def remove_entry entry = JournalEntry.find(params[:id]) update_page do |page| page[entry.dom_id].remove end end

    Creating nodes with Javascript DOM

        var newa=document.createElement('a');
        newa.className="class";
        var newimg=document.createElement('img');
        newimg.src="./image.png";
        newimg.alt="Image name";
        newimg.className="Image class";
        newa.appendChild(newimg);
        newa.href="#";
    
    « Newer Snippets
    Older Snippets »
    11 total  XML / RSS feed