Facebook Comments - Simple and not duplicating on all posts

How to insert Facebook comments in blogger without complication, not duplicating. Easy and simple.

1) Model > Edit HTML > Go > Expand Widget Models

2) Search </head> , and open body tag

3) Paste after open <body> before other tags:
<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/pt_BR/all.js#xfbml=1";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

4) In any place of your code, where you want comments block write:
<div class="fb-comments" data-href="data:post.url" data-num-posts="10" data-width="470"></div>
5) If this way dont word, try this:
<div class="fb-comments" expr:data-href="data:post.url" data-num-posts="10" data-width="470"></div>

Just this.

If this tip works to you comment or share in social networks.

ERR_CONTENT_DECODING_FAILED in Google Chrome

I've a problem with Google Chrome Navigator in my site www.tadarank.com and www.ofertamagica.com.br

Chrome don't show the page, but this error:

Error 330 (net::ERR_CONTENT_DECODING_FAILED)

Looking this problem on Google, i've found many solutions (including reinstall Chrome).

The solution that works for me was relationed with Zip compression on website.

I made some tests and solved my problem changing headers.

In PHP, i change the header:

header('Content-Encoding: gzip, deflate');

to

header('Content-Encoding: zlib, deflate, gzip');

No more psroblems with Google Chrome / ERR_CONTENT_DECODING_FAILED. I hope that this solution work to you too.

Sorry my poor "engrish".

Get google (yahoo, bing) search by Javascript

If somebody need:

A small function to Get google (yahoo, bing) search's by Javascript.

keyword = function(){
 var dr=d.referrer,q,fq,goo='';
 if(dr.match(/ogle\.c|ahoo\.c|bing.c/i)){
  if((q=dr.indexOf('q='))>0){
   fq = dr.indexOf('&',q);
   goo = dr.substring(q+2,(fq>q?fq:dr.length));
  }
 }
 return goo;
}


To use, just call "keyword":

var palavrachave = keyword();
if(palavrachave){
  alert("Hi, welcome to my website. You are searching " + palavrachave);
}


Bye.

Ultimate Micox Menu drop-down CSS - 4 levels

Hi, now a code to be easy make your css drop down menu.

Long time ago i'm finding a perfetc css menu drop down code.
I want a dropdown css menu easy to copy/paste, fast and no difficult configurations.
Just set width, color, bg and ready. Working in FF, IE6/7 an Opera.

Yesterday i post the final part that my code need (activating hover in IE6).
See the online example (and source code) of Ultimate Micox Menu Drop Down CSS - 4 levels.

The codes:
First, make your old UL e LI menu.

<ul>
 <li>class='menu-hv'</li>
 <li><a href='#'>2</a></li>
 <li><a href='#'>3...</a>
  <ul style='background-color: red; '>
   <li>31</li>
   <li><a href='#'>32</a></li>
   <li>33</li>
  </ul>
 </li>
 <li><a href='#'>4...</a>
  <ul>
   <li>41</li>
   <li><a href='#'>42</a></li>
   <li><a href='#'>43...</a>
    <ul  style='background-color: blue'>
     <li>431</li>
     <li><a href='#'>432...</a>
      <ul  style='background-color: gray'>
       <li>4321</li>
       <li><a href='#'>4322</a></li>
      </ul>
     </li>
    </ul>
   </li>
   <li>44</li>
  </ul>
 </li>
</ul>

Second, put the class 'menu-hv' in your UL (or in parent div of UL) to activate horizontal-vertical menu. To vertical-vertical menu the class name is 'menu-vv'.

<ul class='menu-hv'>

Finally, put the code of Ultimate Micox Menu drop-down CSS (UMMDDCSS heheheh) in your CSS code or file. You can edit font, color, width, etc of menu itens in indicated place of my code.

/*
  Menus drop-down horizontal-vertical (hv) e vertical-vertical (vv) 4 levels
  by Micox - elmicoxcodes.blogspot.com - Ver. 2.0 - 20/02/08 - Creative Commons License
*/    
.menu-hv, .menu-vv { position: relative; margin: 0; padding: 0; display: block; zoom: 1;}
 .menu-hv * ,    .menu-vv * { margin: 0; padding: 0 ; list-style: none}
 .menu-hv li ,   .menu-vv li { position: relative; line-height: 1.2em; vertical-align: top }
 .menu-hv a ,    .menu-vv a { display: block; zoom: 1; line-height: 1.2em }
 .menu-hv li ul, .menu-vv li ul { position: absolute; visibility: hidden  }
 .menu-hv li:hover ul,  .menu-vv li:hover ul,
 .menu-hv li.hover ul,  .menu-vv li.hover ul { visibility: visible }
 .menu-hv li:hover ul ul,  .menu-vv li:hover ul ul,
 .menu-hv li.hover ul ul,  .menu-vv li.hover ul ul { visibility: hidden }
 .menu-hv li li:hover ul,  .menu-vv li li:hover ul,
 .menu-hv li li.hover ul,  .menu-vv li li.hover ul { visibility: visible }
 .menu-hv li li:hover ul ul,  .menu-vv li li:hover ul ul,
 .menu-hv li li.hover ul ul,  .menu-vv li li.hover ul ul { visibility: hidden }
 .menu-hv li li li:hover ul,  .menu-vv li li li:hover ul,
 .menu-hv li li li.hover ul,  .menu-vv li li li.hover ul { visibility: visible }
 /* horizontal-vertical */
 .menu-hv:after, .menu-hv.after { content: "."; line-height: 0px; clear: both; display: block; visibility: hidden}
 .menu-hv li { float: left; }  
 .menu-hv li ul li { float: none; }
 .menu-hv li ul li ul { position: absolute; left: 100%; top: 0; }
 /* vertical-vertical */
 .menu-vv { float: left; } 
 .menu-vv li ul { left: 100%; top: 0; }
 /* ****************************************
   Define width, color, bg, etc ABOVE or clear this line if will define in other place
 */
 .menu-hv li { width: 100px; background-color: yellow }
 .menu-vv li { width: 100px; background-color: yellow }
 .menu-hv li a:hover { background-color: cyan }
 .menu-vv li a:hover { background-color: cyan }

 
/* Micox Pseudo-class-css2 to IE (MXPC). Activate .hover and .first-child in IE 6
   http://elmicox.blogspot.com/2008/03/ativando-hover-e-first-child-no-ie-6-um.html */
* html * { color: expression( (function(who){ if(!who.MXPC){
 who.MXPC = '1';
 if(who.nodeName != 'A'){
  who.onmouseenter=function(){ who.className += ' hover'};
  who.onmouseleave=function(){ who.className = who.className.replace(' hover','')}; }
 (who==who.parentNode.firstChild) ? who.className += ' first-child' : '' ;
} } )(this) , 'auto') }

Ready! Comments please.

New way to hover and first-child in IE6

Hi, i'm back

Now, i show a new way to simulate pseudo-class first-child and hover in IE6 with a diferent method. No HTC, no tag script, no external file.

The advantage of my new code is that can be inserted directly in CSS and not needs another file. The idea of "expression" can be used to other implementations :).

Micox Pseudo-class-css2 to IE (MXPC)

/* Micox Pseudo-class-css2 to IE (MXPC). Activate .hover and .first-child in IE 6 */
* html * { color: expression( (function(who){ if(!who.MXPC){
 who.MXPC = '1';
 if(who.nodeName != 'A'){
  who.onmouseenter=function(){ who.className += ' hover'};
  who.onmouseleave=function(){ who.className = who.className.replace(' hover','')}; }
 (who==who.parentNode.firstChild) ? who.className += ' first-child' : '' ;
} } )(this) , 'auto') }

/* example */
p:first-child , p.first-child { color: red }
li:hover a , li.hover a { background-color: blue }

How to use? Just put on top of your css code and use classes .hover and .first-child with the :hover and :first-child. See a online EXAMPLE page and code source.

p:hover , p.hover { color: red }

Comments please.

Script word-wrap to Firefox - updated version

Hello,

Now a new and revised version of my old script to word-wrap big words in Firefox. Correctly tested in Firefox and Opera. No more bugs in children or parents elements. More easy to use.

The Firefox dont wrap big words like Internet Explorer. IE have a CSS property called word-wrap that can be set to 'break-word' and break the big words. Firefox and Opera don't have this property yet. This script simulates this property in elements that have class name set to "word-wrap".

How to use:

1. Get the script in http://naironjcg.googlepages.com/micoxWordWrap.js (4kb)

2. Call this script in your html document: <script type='text/javascript' src='micoxWordWrap.js'></script>

3. Put class name 'word-wrap' in elements (or parents of this element) that you wanna break words. Example: <p class="word-wrap">

Example above:

<head>
<script type='text/javascript' src='micoxWordWrap.js'></script>
<style>
#url {
width: 400px;
padding: 20px;
border: 1px solid green;
}
</style>
</head>
<body>
<div style='width: 350px; border: 1px dotted green;' class='word-wrap'>
<h3>Class word-wrap used just on some parent:</h3>
<p>Normal words Normal words Normal words Normal words Normal words </p>
<p>BigWordBigWordBig<br />
WordBigWordBigWordBigWordBigWordBigWordBigWordBigWordBigWordBigWordBigWordBigWordBigWordBigWordBigWordBigWord</p>
<p><a href='http://elmicoxcodes.blogspot.com'>BigWordAroundedByLink(tagInside)<br />  BigWordAroundedByLink(tagInside)BigWordAroundedByLink(tagInside)BigWordAroundedByLink(tagInside)BigWordAroundedByLink(tagInside)</a></p>
</div>
<div style='width: 350px; border: 1px dotted green; padding: 20px;'>
<h3>Class word-wrap used directly in children tags:</h3>
<p class="word-wrap">Normal words Normal words Normal words Normal words Normal words </p>
<p class="word-wrap">BigWordAroundedByLink (tagInside)BigWordAroundedByLink(tagInside)BigWordAroundedByLink(tagInside)BigWordAroundedByLink(tagInside)BigWordAroundedByLink(tagInside)</p>
<p class="word-wrap"><a href='http://elmicoxcodes.blogspot.com'>BigWordAroundedByLink (tagInside)BigWordAroundedByLink(tagInside)BigWordAroundedByLink(tagInside)BigWordAroundedByLink(tagInside)BigWordAroundedByLink(tagInside)</a></p>
</div>
<div id='result'>aaa </div>
</body>

Ready finish. Bugs, please tell-me.

Vote this link in DZone.

Sorry my bad english.

If you want see my script and make modifications:

/**
* Micox Word Wrap 2.0
* elmicoxcodes.blogspot.com - www.ievolutionweb.com - micoxjcg@yahoo.com.br
* Creative Commons License - creativecommons.org
*
* Description:
* Wraps large words in Firefox and Opera.
* Works just like the word-wrap: break-word; CSS property in Internet Explorer
*
* Usage:
* 1) Include this JS file in your page. Example: 
* 2) Set 'word-wrap' as the classname of the elements that you want to word break. Example: 

* **/ function wrap(quem){ var larg_total,larg_carac,quant_quebra,pos_quebra, over_orig; var elementos,quem, pai, caracs, texto, pai_texto, display_orig, wid_orig; if(quem.nodeType==3){ //elemento tipo texto. tenho que verificar se o pai dele tá quebrando if(quem.nodeValue.replace('\n','').replace('\t','').trim()==''){ //se o textNode for vazio, não prossigo return true; } pai = quem.parentNode; texto = quem.nodeValue; //pegando a largura setada oficial display_orig = pai.style.display; over_orig = pai.style.overflow; wid_orig = pai.style.width; pai.style.display="block"; pai.style.overflow="hidden"; larg_oficial = pai.offsetWidth; //pegando a largura real total pai.style.display="table"; pai.style.width = "auto"; //para o Opera pai.style.overflow = "visible"; larg_total = pai.offsetWidth; //alert("texto: " + texto + " \r\n larg_oficial:" + larg_oficial + " \r\n larg_total:" + larg_total) pai.style.overflow = over_orig; if(larg_total>larg_oficial){ //se o pai do text tá extrapolando, quebro o text pos_quebra = 0; caracs = pai.textContent.length; //recalculando a largura real tirando os espaços pra poder calcular // direito a largura dos caracs e quando vou quebrar quem.nodeValue = pai.textContent.replace(/ /g,"Ø") + " "; larg_total = pai.offsetWidth; pai.style.display = display_orig; larg_carac = larg_total / caracs ; quant_quebra = parseInt(larg_oficial/larg_carac) - 2; quant_quebra = quant_quebra>0 ? quant_quebra : 1 ; quem.nodeValue = ''; while(pos_quebra<=caracs){ quem.nodeValue += texto.substring(pos_quebra,pos_quebra + quant_quebra) + " " pos_quebra = pos_quebra + quant_quebra; } } pai.style.display = display_orig; pai.style.display = over_orig; pai.style.width = wid_orig; }else if(quem.childNodes.length==1 && quem.childNodes[0].nodeType==3){ //é o último do nível e o único filho é texto texto = String(quem.innerHTML); //salvando o original /*quem.innerHTML = " " display_orig = quem.style.display; quem.style.display="block"; larg_oficial = quem.offsetWidth; quem.style.display="table"; quem.innerHTML = texto; larg_total = quem.offsetWidth;*/ //pegando a largura setada oficial display_orig = quem.style.display; over_orig = quem.style.overflow; wid_orig = quem.style.width; quem.style.display="block"; quem.style.overflow="hidden"; larg_oficial = quem.offsetWidth; //pegando a largura real total quem.style.display="table"; quem.style.width = "auto"; //para o Opera quem.style.overflow = "visible"; larg_total = quem.offsetWidth; //alert("texto: " + texto + " \r\n larg_oficial:" + larg_oficial + " \r\n larg_total:" + larg_total) quem.style.overflow = over_orig; if(larg_total>larg_oficial){ //quebrando quem extrapolou pos_quebra = 0; caracs = texto.length; //recalculando a largura real tirando os espaços pra poder calcular // direito a largura dos caracs e quando vou quebrar quem.innerHTML = quem.innerHTML.replace(/ /g,"Ø"); larg_total = quem.offsetWidth; larg_carac = larg_total / caracs ; quant_quebra = parseInt(larg_oficial/larg_carac) - 2; quant_quebra = quant_quebra>0 ? quant_quebra : 1 ; quem.innerHTML = "" while(pos_quebra<=caracs){ quem.innerHTML += texto.substring(pos_quebra,pos_quebra + quant_quebra) + " " pos_quebra = pos_quebra + quant_quebra; } } quem.style.display = display_orig; quem.style.display = over_orig; quem.style.width = wid_orig; }else if(quem.childNodes.length>0){ //se tiver mais que um filho, vou ter que executar de filho em filho nele for(var i=0;i<quem.childNodes.length;i++){ wrap(quem.childNodes[i]); } } } function wordWrap(){ var elementos = document.body.getElementsByTagName("*") if(navigator.appName.indexOf("Internet Explorer")>-1){ for(var i=0; i<elementos.length;i++){ if(elementos[i].className.indexOf("word-wrap")>-1){ elementos[i].style.wordWrap = "break-word"; } } }else{ for(var i=0; i<elementos.length;i++){ if(elementos[i].className.indexOf("word-wrap")>-1){ wrap(elementos[i]); } } } } String.prototype.trim = function() { //Trim ambas direcciones return this.replace(/^[ ]+|[ ]+$/g,""); } function bodyOnReady(func){ //call the function when DOM loaded //http://www.elmicox.com/2007/evento-body-onready-sem-o-uso-de-libs/ //by Micox - www.elmicox.com - elmicox.blogspot.com - webly.com.br if(!(document.body==null)){ func(); }else{ var func_rep = func; setTimeout(function(){ bodyOnReady(func_rep) },100); } } bodyOnReady(wordWrap);

For prototype followers (by Franco Sabbatini - thanks)

function wordWrap(){
//Original by Micox - elmicoxcodes.blogspot.com
//Adapted to Prototype by Franco Sabbatini
 elementos = $$('.word-wrap');
 elementos.each(
    function(elemento){
     if(Prototype.Browser.Gecko){
      if(elemento.hasClassName('word-wrap')){
       texto = elemento.innerHTML.gsub(' ', 'Ø');
       elemento.innerHTML = ' ';
       original = elemento.style.display;
       elemento.style.display='block';
       largo = elemento.offsetWidth;
       elemento.style.display='table';
       elemento.innerHTML = texto;
       largo_total = elemento.offsetWidth;

       pos_quiebre = 0;
       caracteres = texto.length;
       texto = elemento.innerHTML.gsub('Ø', ' ');
       largo_caracteres = largo_total/caracteres;
       if(largo_total>largo){
        cantidad_quiebra = parseInt(largo/largo_caracteres);
        cantidad_quiebra = cantidad_quiebra - (parseInt(cantidad_quiebra/6));
        elemento.innerHTML = '';
        while(pos_quiebre<=caracteres){
          elemento.innerHTML = elemento.innerHTML +
texto.substring(pos_quiebre, pos_quiebre + cantidad_quiebra) + ' ';
          pos_quiebre += cantidad_quiebra;
        }
       } else {
        elemento.innerHTML = texto;
       }
       elemento.style.display = original;
      }
     }
    }
 );
}

htmlEntities, array_search and strip_tags in JavaScript

Small post, small functions :-) Can be helpful for somebody someday.

htmlEntities, Array_search and strip_tags to Java Script (like PHP functions htmlEntities, array_search and strip_tags).

htmlEntities in Javascript

Sometimes you need convert all applicable characters to HTML entities, also in javascript. Very common use while working with Ajax.

A small diference of this function to php original function is the parameters and that, in this function, i change the original char to numeric entitie.

Example: in PHP htmlEntities, 'ã' will turn &atilde;
In this function will turn &#228;

In both cases you will see 'ã' on browser. This can be very useful in Latin languages

function htmlEntities(texto){
    //by Micox - elmicoxcodes.blogspot.com - www.ievolutionweb.com
    var i,carac,letra,novo='';
    for(i=0;i<texto.length;i++){
        carac = texto[i].charCodeAt(0);
        if( (carac > 47 && carac < 58) || (carac > 62 && carac < 127) ){
            //se for numero ou letra normal
            novo += texto[i];
        }else{
            novo += "&#" + carac + ";";
        }
    }
    return novo;
}

Example:

document.getElementById('div_teste').innerHTML = htmlEntities('coração melão');

array_search in Javascript

Now array_search to javascript.

Searches the array for a given value and returns the corresponding key if successful.

function array_search(needle,haystack){
    //by Micox - elmicoxcodes.blogspot.com - www.ievolutionweb.com
    //ve se determinado valor existe no array e retorna sua chave
    for(var i in haystack){
        if(haystack[i]==needle){return i;}    
    }
    return false;
}

Example:

var where_is_pamela = array_search('pamela anderson', arr_hot_girls);

Strip tags in javascript

Continuing with strip_tags to javascript. This function is based in this post.

Strip HTML and PHP tags from a string;

function strip_tags($text){
 return $text.replace(/<\/?[^>]+>/gi, '');
}

 

Simple functions that can be useful someday. Thanks. Bye.

Activating option disabled in IE

In Internet Explorer, the attribute "disabled" fails if used in tag option. See here a javascript to simulate the "disabled" attribute in Internet Explorer.

This code will execute and disable option in Standard browsers (FF, Op, etc):

<select>
   <option>opt 1</option>
   <option disabled="'disabled'">opt 2</option>
   <option>opt 3</option>
</select>

In IE, it will fail.

The above code, simulates the attribute "disabled" to IE, using JavaScript. Try-it:

<!--[if lte IE 7]>
<script>
function ativaOptionsDisabled(){
    var sels = document.getElementsByTagName('select');
    for(var i=0; i < sels.length; i++){
        sels[i].onchange= function(){ //pra se mudar pro desabilitado
            if(this.options[this.selectedIndex].disabled){
                if(this.options.length<=1){
                    this.selectedIndex = -1;
                }else if(this.selectedIndex < this.options.length - 1){
                    this.selectedIndex++;
                }else{
                    this.selectedIndex--;
                }
            }
        }
        if(sels[i].options[sels[i].selectedIndex].disabled){
            //se o selecionado atual é desabilitado chamo o onchange
            sels[i].onchange();
        }    
        for(var j=0; j < sels[i].options.length; j++){ //colocando o estilo
            if(sels[i].options[j].disabled){
                sels[i].options[j].style.color = '#CCC';
            }
        }
    }
}
window.attachEvent("onload", ativaOptionsDisabled)
</script>
<![endif]-->

Update: See other good solutions in comment box above too!

Ok. Now its just call this function in document load

<body onload='ativaOptionsDisabled()'>

Loading a RSS XML feed just using JavaSript

Continuating the post Manipulating XML using JavaScript, now a util example of XML + JavaScript: Loading a RSS XML feed.

1) Manipulating XML using JavaScript

See my previous small tutorial about XML + JavaScript to understend the function above.

2) Making the function to read RSS data

Put the JavaScript function above in your html document or in a ".js" file (and include in your document).

function xmlMicoxRSS(xmlNode){
 //by Micox: http://elmicoxcodes.blogspot.com
 var retorno = "";
 var objNodeList = xmlNode.getElementsByTagName("item")
 for(var i=0;i<objNodeList.length;i++){
  var strTitulo = ""
  var strURL = ""
  var strDescr = ""
  var objNode = objNodeList[i];
  if(objNode.nodeType == 1){//ignore white spaces
   for(var j=0;j<objNode.childNodes.length;j++){
    var objNode2 = objNode.childNodes[j];
    if(objNode2.nodeType == 1){//ignore white spaces
     switch (objNode2.nodeName) {
      case "title": 
       //alert(objNode.childNodes[j].firstChild.nodevalue);
       strTitulo = objNode2.firstChild.nodeValue; 
       break;
      case "link": 
       strURL = objNode2.firstChild.nodeValue; 
       break;
      case "description": 
       strDescr = objNode2.firstChild.nodeValue; 
       break;
     }
    }
   }
   retorno += " <li><a href='" + strURL + "'>" + strTitulo + "</a><br />" + strDescr + "</li>\n";
  }
 }
 retorno = "<ul>\n" + retorno + "</ul>";
 return retorno;
}

3) Now, put the return to your DIV

First, call the function xmlMicoxLoader (previous post) and give to div the return of function xmlMicoxRSS.

xml = xmlMicoxLoader("rss.xml"); //load xml
document.getElementById(div_alvo).innerHTML = xmlMicoxRSS(xml); //list rss

Important: JavaScript just load file in your domain for security reasons.

Another example of XML + Javascript: Dynamic Graphs with Ajax and XML.

Bugs, tests and doubts, comment here :) Sorry my bad english.

Asynchronous upload - Like AJAX - 1 function

Helo! Here a simple function to asynchronous upload using iframe. Dont reload the page. Like AJAX but its not ajax.You dont need to create the iframe, the function do this. Work like Gmail upload and Google pages upload.

Tested in Firefox 2.0, Internet Explorer 6.0 e Opera 9.1. If you test in another browsers, please write a comment.

Update: New version here (portuguese)

1) Put the code above in a file called micoxUpload.js

/* standard small functions */
function $m(quem){
 return document.getElementById(quem)
}
function remove(quem){
 quem.parentNode.removeChild(quem);
}
function addEvent(obj, evType, fn){
 // elcio.com.br/crossbrowser
    if (obj.addEventListener)
        obj.addEventListener(evType, fn, true)
    if (obj.attachEvent)
        obj.attachEvent("on"+evType, fn)
}
function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, fn );
  } else {
    obj.removeEventListener( type, fn, false ); }
} 
/* THE UPLOAD FUNCTION */
function micoxUpload(form,url_action,id_element,html_show_loading,html_error_http){
/******
* micoxUpload - Submit a form to hidden iframe. Can be used to upload
* Use but dont remove my name. Creative Commons.
* Versão: 1.0 - 03/03/2007 - Tested no FF2.0 IE6.0 e OP9.1
* Author: Micox - Náiron JCG - elmicoxcodes.blogspot.com - micoxjcg@yahoo.com.br
* Parametros:
* form - the form to submit or the ID
* url_action - url to submit the form. like action parameter of forms.
* id_element - element that will receive return of upload.
* html_show_loading - Text (or image) that will be show while loading
* html_error_http - Text (or image) that will be show if HTTP error.
*******/

 //testing if 'form' is a html object or a id string
 form = typeof(form)=="string"?$m(form):form;
 
 var erro="";
 if(form==null || typeof(form)=="undefined"){ erro += "The form of 1st parameter does not exists.\n";}
 else if(form.nodeName.toLowerCase()!="form"){ erro += "The form of 1st parameter its not a form.\n";}
 if($m(id_element)==null){ erro += "The element of 3rd parameter does not exists.\n";}
 if(erro.length>0) {
  alert("Error in call micoxUpload:\n" + erro);
  return;
 }

 //creating the iframe
 var iframe = document.createElement("iframe");
 iframe.setAttribute("id","micox-temp");
 iframe.setAttribute("name","micox-temp");
 iframe.setAttribute("width","0");
 iframe.setAttribute("height","0");
 iframe.setAttribute("border","0");
 iframe.setAttribute("style","width: 0; height: 0; border: none;");
 
 //add to document
 form.parentNode.appendChild(iframe);
 window.frames['micox-temp'].name="micox-temp"; //ie sucks
 
 //add event
 var carregou = function() { 
   removeEvent( $m('micox-temp'),"load", carregou);
   var cross = "javascript: ";
   cross += "window.parent.$m('" + id_element + "').innerHTML = document.body.innerHTML; void(0); ";
   
   $m(id_element).innerHTML = html_error_http;
   $m('micox-temp').src = cross;
   //del the iframe
   setTimeout(function(){ remove($m('micox-temp'))}, 250);
  }
 addEvent( $m('micox-temp'),"load", carregou)
 
 //properties of form
 form.setAttribute("target","micox-temp");
 form.setAttribute("action",url_action);
 form.setAttribute("method","post");
 form.setAttribute("enctype","multipart/form-data");
 form.setAttribute("encoding","multipart/form-data");
 //submit
 form.submit();
 
 //while loading
 if(html_show_loading.length > 0){
  $m(id_element).innerHTML = html_show_loading;
 }
 
}

2) Include this file in your HTML

<script type="text/javascript" src="micoxUpload.js"></script>

3) Parameters of micoxUpload function:

  1. form - the form to submit or the ID of a form .
  2. url_action - url to submit the form. like 'action' parameter of forms.
  3. id_element - element that will receive return of upload.
  4. html_show_loading - Text (or image) that will be show while loading
  5. html_error_http - Text (or image) that will be show if HTTP error.

4) Ok. Now you have a lot of forms to call the Asynchronous upload function. 3 Examples:

4.1) Basic from a button (or input-type-button) in a form:

<legend>Basic use</legend>
  <form>
    <input type="file" name="name" />
    <div id="upload_1" class="recebe">&nbsp;</div>
    <button onClick="micoxUpload(this.form,'upa.php','upload_1','Loading...','Error in upload'); return false;" type="button">test</button>
  </form>
</fieldset>

4.2) When input-file lost focus (onblur):

<fieldset>
<legend>On blur use</legend>
  <form>
    <input type="file" name="name" onchange="micoxUpload(this.form,'upa.php','upload_2','Loading...','Error in upload')" />
    <div id="upload_2" class="recebe">&nbsp;</div>
  </form>
</fieldset>

4.3) Making acessible whitout JavaScript :

<fieldset>
<legend>Unobstrusive</legend>
    <form action="upa.php" target="_blank">
    <input type="file" name="name" onchange="micoxUpload(this.form,'upa.php','upload_3','Loading...','Error in upload')" />
    <div id="upload_3" class="recebe">&nbsp;</div>
    <button type="submit">Go</button>
  </form>
</fieldset>

Ok. Bugs, errors, comment here.
In next post, a more flexible version of this function for who understend JavaScript.

Portuguese version: Upload Assíncrono (iframe como AJAX) - 1 função simples

Manipulating XML using JavaScript

No PHP, ASP or JSP codes, just JavaScript.

Manipulating XML files or data using JavaScript to create lists, tables, menus, manipulate feeds (rss or atom), etc.

Important: Browser just allow access to files in your own domain (security reasons). Dont try to load XML files of another domains, this is not possible.

1. Make a XML test file

<?xml version="1.0" ?>
<person>
   <ident id="1">
    <name>John</name>
    <email>John@mail.com</email>
   </ident>
   <ident id="2">
    <name family="ze" data="2">Maria</name>
    <email>maria@mail.com</email>
   </ident>
</person>

Save as names.xml

2. Loading XML

The browsers load XML files using diferent ways (like in Ajax). Internet Explorer (IE) use ActiveX. Firefox and Opera use XMLHttpRequest (and another ways).

The code to return a XML object to these browsers is:

function xmlMicoxLoader(url){
  //by Micox: micoxjcg@yahoo.com.br.
  //http://elmicoxcodes.blogspot.com
    if(window.XMLHttpRequest){
        var Loader = new XMLHttpRequest();
        //assyncronous mode to load before the 'return' line
        Loader.open("GET", url ,false); 
        Loader.send(null);
        return Loader.responseXML;
    }else if(window.ActiveXObject){
        var Loader = new ActiveXObject("Msxml2.DOMDocument.3.0");
        //assyncronous mode to load before the 'return' line
        Loader.async = false;
        Loader.load(url);
        return Loader;
    }
}

Using assyncronous mode to load before the 'return' line.

More informations about responseXML (in portuguese): a propriedade responseXML.

3. Manipulating XML - Example

XML can be manipulated like a tree using DOM functions and properties: childNodes, nodeType, nodeValue, firstChild, etc. To see more functions read MDC DOM docs.

In example code bellow, i read all childs of XML returned by xmlMicoxLoader. Get values using "nodeValue", names using "nodeName" and attributes using array "attributes[]".

Very important: IE ignores white spaces in XML file, but to Opera and Firefox, these white spaces are valid childNodes (#text nodes). To filter these elements we using a nodetype test (real XML elements have nodeType=1, #texts have nodeType=3).

This example code print a XML tree. Read and understends:

function xmlMicoxTree(xmlNode,ident){
  //by Micox: micoxjcg@yahoo.com.br
    var treeTxt=""; //var to content temp
    for(var i=0;i<xmlNode.childNodes.length;i++){//each child node
  if(xmlNode.childNodes[i].nodeType == 1){//no white spaces
   //node name
   treeTxt = treeTxt + ident + xmlNode.childNodes[i].nodeName + ": "
   if(xmlNode.childNodes[i].childNodes.length==0){
    //no children. Get nodeValue
    treeTxt = treeTxt + xmlNode.childNodes[i].nodeValue 
    for(var z=0;z<xmlNode.childNodes[i].attributes.length;z++){
     var atrib = xmlNode.childNodes[i].attributes[z];
     treeTxt = treeTxt + " (" + atrib.nodeName + " = " + atrib.nodeValue + ")";
    }
    treeTxt = treeTxt + "<br />\n";
   }else if(xmlNode.childNodes[i].childNodes.length>0){
    //children. get first child
    treeTxt = treeTxt + xmlNode.childNodes[i].firstChild.nodeValue;
    for(var z=0;z<xmlNode.childNodes[i].attributes.length;z++){
     var atrib = xmlNode.childNodes[i].attributes[z];
     treeTxt = treeTxt + " (" + atrib.nodeName + " = " + atrib.nodeValue + ")";
    }
    //recursive to child of children
    treeTxt = treeTxt + "<br />\n" + xmlMicoxTree(xmlNode.childNodes[i],ident + "> > ");
   }
      }
    }
    return treeTxt;
}

Call the functions:

xml = xmlMicoxLoader("names.xml"); //load xml
document.write(xmlMicoxTree(xml,"")); //print the tree 

4) Loading RSS

In the next post, a real example: loading a RSS XML feed just using JavaSript

---
Another way to load XML using JavaScript in IBM website.

Portuguese original version.

Include Function in JavaScript

Here, a include function to JavaScript like PHP.

Good for conditional includes.

Using:

if(have_money==true)  {
 include("girs.js");
} else if(i_am_very_rich==true) {
 include("more_more_girls.js");
}else if(i_am_inteligent==true){
 include("no_girls_back_to_work.js");
}

Add this function to your code:

function include(arquivo){
//By Fabrício Magri e Micox
//http://elmicox.blogspot.com/2006/12/include-em-javascript.html
 var novo = document.createElement('script');
 novo.setAttribute('type', 'text/javascript');
 novo.setAttribute('src', arquivo);
 document.getElementsByTagName('head')[0].appendChild(novo);
 //apos a linha acima o navegador inicia o carregamento do arquivo
 //portanto aguarde um pouco até o navegador baixá-lo. :)
}

Tested sucessful in Internet Explorer 6.0, Firefox 2.0 and Opera 8.5.

Edit 02/08/07: A include_once function can be viewed here.

Bugs and comments? Just comment :) Bye.

Portuguese original version and comments.

InnerHTML and Select option in IE

Hello. This is my second post.

The non-DOM property innerHTML can't add options to a tag select in Internet Explorer.

Example not working:

document.getElementById("my_select").innerHTML = "<option value='1'>not</option> <option value='2'>work</option>"; 

The correct way to insert options in a select is using appendChild or addOption functions. But that's tiring if we are working with Ajax.

Use innerHTML is not the standard but it is very useful.

The function above, will help you to insert options like using innerHTML, in IE, Firefox or Opera.

Updated: now supports option-selected

Using my function:

var inner = "<option value='1'>Now</option> <option value='2'>work</option>"; 
select_innerHTML(document.getElementById("my_select"),inner);

The function. Add to your lib.

function select_innerHTML(objeto,innerHTML){
/******
* select_innerHTML - corrige o bug do InnerHTML em selects no IE
* Veja o problema em: http://support.microsoft.com/default.aspx?scid=kb;en-us;276228
* Versão: 2.1 - 04/09/2007
* Autor: Micox - Náiron José C. Guimarães - micoxjcg@yahoo.com.br
* @objeto(tipo HTMLobject): o select a ser alterado
* @innerHTML(tipo string): o novo valor do innerHTML
*******/
    objeto.innerHTML = ""
    var selTemp = document.createElement("micoxselect")
    var opt;
    selTemp.id="micoxselect1"
    document.body.appendChild(selTemp)
    selTemp = document.getElementById("micoxselect1")
    selTemp.style.display="none"
    if(innerHTML.toLowerCase().indexOf("<option")<0){//se não é option eu converto
        innerHTML = "<option>" + innerHTML + "</option>"
    }
    innerHTML = innerHTML.toLowerCase().replace(/<option/g,"<span").replace(/<\/option/g,"</span")
    selTemp.innerHTML = innerHTML
      
    
    for(var i=0;i<selTemp.childNodes.length;i++){
  var spantemp = selTemp.childNodes[i];
  
        if(spantemp.tagName){     
            opt = document.createElement("OPTION")
    
   if(document.all){ //IE
    objeto.add(opt)
   }else{
    objeto.appendChild(opt)
   }       
    
   //getting attributes
   for(var j=0; j<spantemp.attributes.length ; j++){
    var attrName = spantemp.attributes[j].nodeName;
    var attrVal = spantemp.attributes[j].nodeValue;
    if(attrVal){
     try{
      opt.setAttribute(attrName,attrVal);
      opt.setAttributeNode(spantemp.attributes[j].cloneNode(true));
     }catch(e){}
    }
   }
   //getting styles
   if(spantemp.style){
    for(var y in spantemp.style){
     try{opt.style[y] = spantemp.style[y];}catch(e){}
    }
   }
   //value and text
   opt.value = spantemp.getAttribute("value")
   opt.text = spantemp.innerHTML
   //IE
   opt.selected = spantemp.getAttribute('selected');
   opt.className = spantemp.className;
  } 
 }    
 document.body.removeChild(selTemp)
 selTemp = null
}

Another solution to innerHTML/Select/IE problem, here

Portuguese original version.

Word wrap in Firefox

Updated version of word-wrap to Firefox and Opera here!!! Above, a old version with bugs.

Hello. My first topic.
This blog will show just codes.

I have a blog in portuguese language and decide post my codes in english to all the word heheh.
My english is not good, so, sorry and go to codes. Just codes.

The Firefox dont wrap big words like Internet Explorer in width of a parent element.
Example:

This code

<style>
#url {
width: 400px;
}
</style>
<div id="url">
    <p>URL:</p>
    <p>http://www.google.com.br/search?hl=pt-BR&q=blableblibloblu&btnG=Pesquisa+Google&meta= </p>
</div>

In IE will render like

URL
http://www.google.com.br/search?hl=pt-
BR&q=plugsites&btnG=Pesquisa+Google&meta=

And the Firefox will render like

URL
http://www.google.com.br/search?hl=pt-BR&q...Pesquisa+Google&meta=

This is a problem. The declarations to word wrap just will come in CSS3.

But try use this code:

<style>
#url { border:1px solid black; width:50px; }
p {border:1px solid blue; }
</style>
<script>
function wordWrap(){
/******
* wordWrap to firefox for big words
* Creative Commons license * Version: 1.0 - 26/04/2006
* Autor: Micox - Náiron J.C.G - micoxjcg@yahoo.com.br - http://elmicoxcodes.blogspot.com
* Uso: call the function on onload of body element.
* put the class "word-wrap" on elements to wordwrap
*******/
    var larg_total,larg_carac,quant_quebra,pos_quebra;
    var elementos,quem, caracs, texto, display_orig;
    
    elementos = document.getElementsByTagName("p")
    
    for(var i=0; i<elementos.length;i++){
        if(elementos[i].className=="word-wrap"){
            quem = elementos[i];
            
            quem.innerHTML = String(quem.innerHTML).replace(/ /g,"Ø")
            texto = String(quem.innerHTML)
            
            quem.innerHTML = " "
            
            display_orig = quem.style.display;
            quem.style.display="block";
            larg_oficial = quem.offsetWidth;
            //alert("oficial: " + larg_oficial)
            //alert("display " + quem.style.display)
            if(!document.all) quem.style.display="table";
            //alert("display " + quem.style.display)
            quem.innerHTML = texto;
            larg_total = quem.offsetWidth;
            //alert("total: " + larg_total)
            
            pos_quebra = 0;
            caracs = texto.length;
            texto = texto.replace(/Ø/g," ")
            larg_carac = larg_total / caracs
            if(larg_total>larg_oficial){
                quant_quebra = parseInt(larg_oficial/larg_carac)
                quant_quebra = quant_quebra - (parseInt(quant_quebra/6)) //quanto menor o num, maior a garantia;
                quem.innerHTML = ""
                while(pos_quebra<=caracs){
                    quem.innerHTML = quem.innerHTML + texto.substring(pos_quebra,pos_quebra + quant_quebra) + " "
                    pos_quebra = pos_quebra + quant_quebra;
                }
            }else{
                quem.innerHTML = texto;
            }//end if do larg_total>larg_oficial
            quem.style.display = display_orig;
        }//end if do word wrap
    }//end for loop dos elementos
}
</script>
<body onload="wordWrap()">
<div id="url">
    <p>URL:</p>
    <p class="word-wrap">lala </p>
    <p class="word-wrap">EstaEUmaLinhaQueDeveraSerQuebradaPoisÉGrandeDemais</p>
    <p  class="word-wrap">EstaEOutraLinha,QueDeveraSerQuebrada.PoisÉGrandeDemais.MasComPontuacao</p>
    <p  class="word-wrap">abc defgh 890123456789012 ijklmnopqrstu 9012345678901 vivaO micox </p>
    <p  class="word-wrap">Vou colocar aqui uma frase comum pragente ver comé que ela se comporta</p>
</div>
</body>

Just add word-wrap classname in elements to wrap

Bye. To the next

Portuguese original version.