jump to navigation

TextArea Mejorado marzo 1, 2007

Posted by superpiwi in Javascript.
trackback

En http://gregtaff.com/misc/editRegions/ me encuentro un control javascript muy interesante. He modificado el codigo para cambiar el funcionamiento de los botones ya que no funcionaban como yo queria. En principio he añadido una variable que almacena el texto original para recuperarlo cuando se pulse el boton “Cancelar”. Y tambien he modificado el texto y funcionamiento de los botones.

textarea01.jpg

Aqui el código (Conectate a la pagina principal del autor, para consultar la licencia de uso).

demo.html


<html>
<head>
<title>EDIT IN PLACE</title>
<script type="text/javascript" src="MouseState.js"></script>
<script type="text/javascript" src="EditRegions.js"></script>
<style type="text/css">
body {width:700px;margin:auto;}
a{color:#41759A;font-weight:bold;text-decoration:none;border-bottom:1px solid #41759A;}
a:visited {color:#820001;border-color:#820001;}
.red{color:black;background:#FCF9D7;font-family:times new roman;padding:10px;margin:30px;}
.edit_edit {background:#FFF;margin:0px;padding:2px;color:#000;}
.editButtons {
background:gray;
float:left;
padding:0px 4px;
margin:2px;
color:#FFF ! important;
text-Decoration:none;
font-Size:.8em;
fontFamily:Arial, Helvetica, sans-serif;
}
.editButtons:hover {
background:#000;
color:#FFF;
}</style>
</head>
<body>
<div style="background:#D4F6FF;padding:10px;min-height:310px;margin-bottom:30px;" >
<b>DEMO TEXTAREA MEJORADO:</b>
<br/>Codigo original de <a href='http://gregtaff.com/misc/editRegions/'>http://gregtaff.com/misc/editRegions/ </a>
<br/>Modificaciones por Jose Delgado, 1 de Marzo 2007
<br/><br/>
<li> Modificado el javascript EditRegions para guardar el texto original del textarea en una variable</li>
<li> Modificado el codigo de los botones para Guardar el texto, recuperar el texto original o limpiar el textarea</li>
<div class="editInPlace red" style="float:right;width:300px;">
Este control sirve para mejorar la apariencia en las cajas de texto que se usan para mostrar descripciones. Click sobre la barra gris para mover el control y click en el ultimo boton para redimensionar. Escribe aqui tu descripcion...
</div></body>
</html>

EditRegions.js

/*
documentation... do to
KEYBOARD SHORTCUTS
[escape] will cancel edit.
[alt][ctrl][s] will save.
*/
function $() {
//
// Just a shortened version of document.getElementById();
// shamelessly ripped from prototype.
//
var results = [], element;
for (var i = 0; i < arguments.length; i++)
{
element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
results.push(element);
}
if(results.length == 1){return results[0]}
return results;
}
function getStyle(el,styleProp)
// notes: retrieves the rendered style attribute [styleProp] of the element [el]
// Equivalent to el.currentStyle[styleProp] in IE and
// document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp)
// in W3C compliant browsers.
// credit: http://www.quirksmode.org/dom/getstyles.html
{
var x = el;
if(typeof x == "string"){x = document.getElementById(x);}
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}
var InPlace = {
elems: new Object(),
createButton: function(caption, ordinal, clickEvent)
{
var thisButton = document.createElement("a");
thisButton.style.position="absolute";
thisButton.style.cursor="pointer";
thisButton.style.display="none";
thisButton.className = "editButtons";
thisButton.href="#";
thisButton.ordinal = ordinal;
thisButton.innerHTML = caption;
thisButton.id = "editButton" + caption + ordinal;
thisButton.onclick = clickEvent;
return thisButton;
},
editButtons: {
hideButtons:function(ordinal){
for(buttons in InPlace.elems[ordinal]["buttons"]){
InPlace.elems[ordinal]["buttons"][buttons].style.display = "none";
}
},
showButtons:function(ordinal){
var xLocation = 1;
for(button in InPlace.elems[ordinal]["buttons"])
{
InPlace.elems[ordinal]["buttons"][button].style.display = "";
InPlace.elems[ordinal]["buttons"][button].style.top = InPlace.elems[ordinal]["edit"].offsetHeight+1;
InPlace.elems[ordinal]["buttons"][button].style.left = xLocation;
xLocation = xLocation + InPlace.elems[ordinal]["buttons"][button].offsetWidth + 2;
}
}
},
initialize: function(tagName)
// notes: find elements of the specified type [tagName]
// cycle through them and find elements in the editInPlace class.
//
// for each found element, create two elements.
// Id them 'editDisplayX' and 'editEditX' where X is the array index.
//
// ensure that each item will display properly, then assign the appropriate behaviors.
// copy content from the original element into the display item and append the two new
// items to the now empty original element - which will then act as a wrapper.
{
if(!tagName){tagName = "*"}
var eipItems = document.getElementsByTagName(tagName);
var itemsCtr
for(itemsCtr = 0; itemsCtr<eipItems.length; itemsCtr++){
if(eipItems[itemsCtr].className.indexOf("editInPlace") != -1){
this.makeEditable(eipItems[itemsCtr], itemsCtr);
}
}
},
beginEdit:function(ordinal)
{
var lastButton = this.elems[ordinal]["buttons"][this.elems[ordinal]["buttons"].length - 1];
this.elems[ordinal]["edit"].style.display = "";
this.elems[ordinal]["displayBorder"].style.display = "";
this.elems[ordinal]["editBorder"].style.display = "";
this.elems[ordinal]["resize"].style.display = "";
this.editButtons.showButtons(ordinal);
this.elems[ordinal]["displayBorder"].style.height = this.elems[ordinal]["display"].offsetHeight;
this.elems[ordinal]["displayBorder"].style.width = this.elems[ordinal]["display"].offsetWidth;
this.elems[ordinal]["displayBorder"].style.top = this.elems[ordinal]["display"].offsetTop;
this.elems[ordinal]["displayBorder"].style.left = this.elems[ordinal]["display"].offsetLeft;
this.elems[ordinal]["editBorder"].style.height = this.elems[ordinal]["edit"].offsetHeight + this.elems[ordinal]["buttons"][1].offsetHeight + 6;
this.elems[ordinal]["editBorder"].style.width = this.elems[ordinal]["edit"].offsetWidth;
this.elems[ordinal]["resize"].style.width = this.elems[ordinal]["buttons"][0].offsetHeight;
this.elems[ordinal]["resize"].style.top = this.elems[ordinal]["edit"].offsetHeight + 3;
this.elems[ordinal]["resize"].style.left = this.elems[ordinal]["edit"].offsetWidth - this.elems[ordinal]["buttons"][0].offsetHeight - 3;
this.elems[ordinal]["resize"].style.height = this.elems[ordinal]["resize"].offsetWidth;
this.elems[ordinal]["move"].style.width = this.elems[ordinal]["edit"].offsetWidth - (lastButton.offsetLeft + lastButton.offsetWidth + this.elems[ordinal]["resize"].offsetWidth + 7);
this.elems[ordinal]["move"].style.top = this.elems[ordinal]["edit"].offsetHeight + 3;
this.elems[ordinal]["move"].style.left = lastButton.offsetLeft + lastButton.offsetWidth + 2;
this.elems[ordinal]["move"].style.height = this.elems[ordinal]["buttons"][0].offsetHeight;
this.elems[ordinal]["edit"].focus();
},
finishEdit:function(ordinal, success)
{
this.elems[ordinal]["edit"].style.display="";
this.elems[ordinal]["display"].style.display="";
this.elems[ordinal]["displayBorder"].style.display = "none";
this.elems[ordinal]["editBorder"].style.display = "none";
this.elems[ordinal]["resize"].style.display = "none";
this.editButtons.hideButtons(ordinal);
if(success){
if(navigator.product != 'Gecko'){this.elems[ordinal]["display"].innerHTML=this.elems[ordinal]["edit"].value.replace(/[\r]/gi,"<br\/>")}
if(navigator.product == 'Gecko'){this.elems[ordinal]["display"].innerHTML=this.elems[ordinal]["edit"].value.replace(/[\r\n]/gi,"<br\/>")}
}
else{
this.elems[ordinal]["edit"].value = this.elems[ordinal]["display"].innerHTML.replace(/[\n\r]/gi,"");
this.elems[ordinal]["edit"].value = this.elems[ordinal]["edit"].value.replace(/<br>/gi,"\r").replace(/<br\/>/gi,"\r");
this.elems[ordinal]["edit"].value = this.elems[ordinal]["edit"].value.replace(/\r\s/gi,"\r").replace(/\x20+/gi," ");
}
},
makeEditable: function(thisItem, ordinal)
{
var displayElm = thisItem;
displayElm.className = thisItem.className.replace(/editInPlace/, "edit_display");
displayElm.ordinal = ordinal;
displayElm.style.cursor = "pointer";
displayElm.onclick = function()
{
window.eval(this.parentNode.getAttribute("onedit"));
InPlace.beginEdit(this.ordinal);
}
var editElm = document.createElement("textarea");
// retouch the value so it will display consitantly between HTML and the textarea.
editElm.value = thisItem.innerHTML.replace(/[\n\r]/gi,"");
editElm.value = editElm.value.replace(/<br>/gi,"\r").replace(/<br\/>/gi,"\r");
editElm.value = editElm.value.replace(/\r\s/gi,"\r").replace(/\x20+/gi," ");
editElm.style.width = thisItem.offsetWidth;
editElm.style.height = thisItem.offsetHeight;
editElm.style.display="none";
editElm.style.border="0px solid black";
editElm.className = "edit_edit";
editElm.id = "editEdit" + ordinal;
editElm.ordinal = ordinal;
editElm.onupdate =function() {window.eval(this.parentNode.getAttribute("onupdate"));}
editElm.onkeypress = function(e){
pressedKey = e ? Math.max(e.keyCode, e.charCode) : window.event.keyCode;
ctrlKey = e ? e.ctrlKey : window.event.ctrlKey;
altKey = e ? e.altKey : window.eventaltKey;
if((pressedKey == 115 || pressedKey == 83) && ctrlKey && altKey){
InPlace.finishEdit(this.ordinal, true)
this.onupdate();
return false;
}
if(pressedKey == 27){
InPlace.finishEdit(this.ordinal, false)
return false;
}
}
editElm.onkeyup = function(e){
var ordinal = this.ordinal;
if(navigator.product != 'Gecko'){InPlace.elems[ordinal]["display"].innerHTML=InPlace.elems[ordinal]["edit"].value.replace(/[\r]/gi,"<br\/>")}
if(navigator.product == 'Gecko'){InPlace.elems[ordinal]["display"].innerHTML=InPlace.elems[ordinal]["edit"].value.replace(/[\r\n]/gi,"<br\/>")}
InPlace.elems[ordinal]["displayBorder"].style.height = InPlace.elems[ordinal]["display"].offsetHeight;
InPlace.elems[ordinal]["displayBorder"].style.width = InPlace.elems[ordinal]["display"].offsetWidth;
InPlace.elems[ordinal]["displayBorder"].style.top = InPlace.elems[ordinal]["display"].offsetTop;
InPlace.elems[ordinal]["displayBorder"].style.left = InPlace.elems[ordinal]["display"].offsetLeft;
}
var displayBorderElm = document.createElement("div");
var editBorderElm = document.createElement("div");
var resizeElm = document.createElement("div");
var moveElm = document.createElement("div");
displayBorderElm.style.position = "absolute";
displayBorderElm.style.border = "1px dashed red";
displayBorderElm.style.display = "none";
editBorderElm.style.position = "absolute";
editBorderElm.style.border = "1px solid black";
editBorderElm.style.background = "#FFF";
editBorderElm.style.display = "none";
editBorderElm.style.top = displayElm.offsetTop; // + displayElm.offsetHeight;
editBorderElm.style.left = displayElm.offsetLeft;
resizeElm.style.position = "absolute";
resizeElm.style.background = "gray";
resizeElm.style.fontSize = "0em";
moveElm.style.position = "absolute";
moveElm.style.background = "#C6C6C6";
moveElm.style.fontSize = "0em";
moveElm.onmousedown = function(e){InPlace.startMove(e,ordinal)};
resizeElm.onmousedown = function(e){InPlace.startSize(e,ordinal)};
// populate our object structure
this.elems[ordinal] = new Object();
this.elems[ordinal]["edit"] = editElm;
this.elems[ordinal]["display"] = displayElm;
this.elems[ordinal]["displayBorder"] = displayBorderElm;
this.elems[ordinal]["editBorder"] = editBorderElm;
this.elems[ordinal]["resize"] = resizeElm;
this.elems[ordinal]["move"] = moveElm;
this.elems[ordinal]["buttons"] = new Array();
//-------------------------------------------------------------------------------------------
// @MODIFICATION 1 Marzo - jdelgado
// Se añade nuevo para guardar el texto anterior y recuperarlo si se pulsa el boton CANCEL
// Se modifica el texto y el codigo de los botones
//-------------------------------------------------------------------------------------------
this.elems[ordinal]["texto_origen"] = editElm.value;
//thisItem.innerHTML;
this.elems[ordinal]["buttons"].push( this.createButton("Guardar", ordinal,
function()
{
// Se guarda, actualizamos el contenido del texto_origen
InPlace.elems[ordinal]["texto_origen"]=InPlace.elems[ordinal]["edit"].value;
InPlace.finishEdit(this.ordinal, true);
$("editEdit"+this.ordinal).onupdate();
return false;
}
)
);
this.elems[ordinal]["buttons"].push( this.createButton("Cancelar", ordinal,
function()
{
InPlace.elems[ordinal]["edit"].value=InPlace.elems[ordinal]["texto_origen"];
//InPlace.finishEdit(this.ordinal, false);
return false;
}
)
);
this.elems[ordinal]["buttons"].push( this.createButton("Eliminar", ordinal,
function()
{
InPlace.elems[ordinal]["edit"].value="";
//InPlace.finishEdit(this.ordinal, false);
return false;
}
)
);
//--------------------------------------------------------------------------------
// FIN DE LA MODIFICACION
//--------------------------------------------------------------------------------
// finally, attach the elements.
document.getElementsByTagName('body')[0].appendChild(displayBorderElm);
document.getElementsByTagName('body')[0].appendChild(editBorderElm);
editBorderElm.appendChild(editElm);
editBorderElm.appendChild(resizeElm);
editBorderElm.appendChild(moveElm);
for(buttons in InPlace.elems[ordinal]["buttons"]){
editBorderElm.appendChild(InPlace.elems[ordinal]["buttons"][buttons]);
}
},
sizeProc: null,
moveProc: null,
startMove: function(e,ordinal)
{
if (!e) var e = window.event;
if (!e.target) e.target = e.srcElement;
var offsetX = (e.offsetX) ? e.offsetX : e.layerX;
var offsetY = (e.offsetY) ? e.offsetY : e.layerY;
offsetX += e.target.offsetLeft;
offsetY += e.target.offsetTop;
eventObserve(document, 'mousemove', MouseState.onmousemove);
eventObserve(document, 'mouseup', InPlace.endMove);
this.moveProc = eventObserve(document, 'mousemove', function(e){InPlace.doMove(e,ordinal, offsetX, offsetY)});
},
doMove: function(e,ordinal,offsetX,offsetY)
{
this.elems[ordinal]["editBorder"].style.top = MouseState.y - offsetY;
this.elems[ordinal]["editBorder"].style.left = MouseState.x - offsetX;
},
endMove: function(e,ordinal)
{
eventStopObserving(document, 'mousemove', MouseState.onmousemove);
eventStopObserving(document, 'mousemove', InPlace.moveProc);
eventStopObserving(document, 'mouseup', InPlace.endMove);
},
startSize: function(e, ordinal)
{
if (!e) var e = window.event;
if (!e.target) e.target = e.srcElement;
var insideOffsetX = (e.offsetX) ? e.offsetX : e.layerX;
var insideOffsetY = (e.offsetY) ? e.offsetY : e.layerY;
var targetWidth = e.target.offsetWidth;
var targetHeight = e.target.offsetHeight;
offsetX = e.target.parentNode.offsetLeft - (targetWidth - insideOffsetX) - 2;
offsetY = e.target.parentNode.offsetTop - (targetHeight - insideOffsetY) - 2;
var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body
var dsocleft=(navigator.product != 'Gecko')? iebody.scrollLeft : pageXOffset
var dsoctop=(navigator.product != 'Gecko')? iebody.scrollTop : pageYOffset
MouseState.x = e.clientX + dsocleft;
MouseState.y = e.clientY + dsoctop;
eventObserve(document, 'mousemove', MouseState.onmousemove);
eventObserve(document, 'mouseup', InPlace.endSize);
this.sizeProc = eventObserve(document, 'mousemove', function(e){InPlace.doSize(e,ordinal, offsetX, offsetY)});
},
doSize: function(e,ordinal,offsetX,offsetY)
{
this.elems[ordinal]["editBorder"].style.height = MouseState.y - offsetY;
this.elems[ordinal]["editBorder"].style.width = MouseState.x - offsetX;
var lastButton = this.elems[ordinal]["buttons"][this.elems[ordinal]["buttons"].length - 1];
editHeight = (MouseState.y - offsetY) - this.elems[ordinal]["buttons"][1].offsetHeight -6;
editWidth = (MouseState.x - offsetX) - 2;
MoveWidth = editWidth - (lastButton.offsetLeft + lastButton.offsetWidth + this.elems[ordinal]["resize"].offsetWidth + 6)
if(editHeight < 80){
MouseState.y = (80 + lastButton.offsetHeight + 6) + offsetY;
this.elems[ordinal]["editBorder"].style.height = 80 + lastButton.offsetHeight + 6;
}
if(MoveWidth < this.elems[ordinal]["buttons"][0].offsetHeight){
MouseState.x = (this.elems[ordinal]["move"].offsetLeft + (lastButton.offsetHeight * 2) + 6) + offsetX;
this.elems[ordinal]["editBorder"].style.width = this.elems[ordinal]["move"].offsetLeft + (lastButton.offsetHeight * 2) + 6;
}
this.elems[ordinal]["edit"].style.height = (MouseState.y - offsetY) - this.elems[ordinal]["buttons"][1].offsetHeight -6;
this.elems[ordinal]["edit"].style.width = MouseState.x - offsetX - 2;
this.elems[ordinal]["resize"].style.width = this.elems[ordinal]["buttons"][0].offsetHeight;
this.elems[ordinal]["resize"].style.top = this.elems[ordinal]["edit"].offsetHeight + 3;
this.elems[ordinal]["resize"].style.left = this.elems[ordinal]["edit"].offsetWidth - this.elems[ordinal]["buttons"][0].offsetHeight - 1;
this.elems[ordinal]["resize"].style.height = this.elems[ordinal]["buttons"][0].offsetHeight;
this.elems[ordinal]["move"].style.width = this.elems[ordinal]["edit"].offsetWidth - (lastButton.offsetLeft + lastButton.offsetWidth + this.elems[ordinal]["resize"].offsetWidth + 5);
this.elems[ordinal]["move"].style.top = this.elems[ordinal]["edit"].offsetHeight + 3;
this.elems[ordinal]["move"].style.left = lastButton.offsetLeft + lastButton.offsetWidth + 2;
this.elems[ordinal]["move"].style.height = this.elems[ordinal]["buttons"][0].offsetHeight;
this.editButtons.showButtons(ordinal);
},
endSize: function(ordinal)
{
eventStopObserving(document, 'mousemove', MouseState.onmousemove);
eventStopObserving(document, 'mousemove', InPlace.sizeProc);
eventStopObserving(document, 'mouseup', InPlace.endSize);
},
browserResize: function(){
for(ordinal in InPlace.elems){
var changeY = InPlace.elems[ordinal]["displayBorder"].offsetTop - InPlace.elems[ordinal]["display"].offsetTop;
var changeX = InPlace.elems[ordinal]["displayBorder"].offsetLeft - InPlace.elems[ordinal]["display"].offsetLeft;
InPlace.elems[ordinal]["editBorder"].style.top = InPlace.elems[ordinal]["editBorder"].offsetTop - changeY;
InPlace.elems[ordinal]["editBorder"].style.left = InPlace.elems[ordinal]["editBorder"].offsetLeft - changeX;
InPlace.elems[ordinal]["displayBorder"].style.height = InPlace.elems[ordinal]["display"].offsetHeight;
InPlace.elems[ordinal]["displayBorder"].style.width = InPlace.elems[ordinal]["display"].offsetWidth;
InPlace.elems[ordinal]["displayBorder"].style.top = InPlace.elems[ordinal]["display"].offsetTop;
InPlace.elems[ordinal]["displayBorder"].style.left = InPlace.elems[ordinal]["display"].offsetLeft;
}
}
}
eventObserve(window,"load", function(){InPlace.initialize('div')});
eventObserve(window,"resize", function(){InPlace.browserResize()});

MouseState.js


// MouseState.js
// Reports the current "State of the Mouse" upon request
function eventObserve(elm, evType, fn, useCapture) {
//
// Cross-browser friendly means of registering event handlers
// Taken from http://www.dustindiaz.com/top-ten-javascript/
//
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return fn;
}
else if (elm.attachEvent) {
elm['e'+evType+fn] = fn;
elm[evType+fn] = function(){elm['e'+evType+fn]( window.event );}
elm.attachEvent( 'on'+evType, elm[evType+fn] );
//var r = elm.attachEvent('on' + evType, fn);
return fn;
}
else {
elm['on' + evType] = fn;
}
}
function eventStopObserving(elm, evType, fn, useCapture) {
//
// Cross-browser friendly means of unregistering event handlers
// bastardized from prototype event.stopObserving, then formatted to jive with eventObserve
//
if (elm.removeEventListener) {
elm.removeEventListener(evType, fn, useCapture);
} else if (elm.detachEvent) {
try {
elm.detachEvent( 'on'+evType, elm[evType+fn] );
elm[evType+fn] = null;
}
catch (e) {}
}
return fn;
}
var buttons = {
//
// mouse buttons
//
left:((navigator.product == 'Gecko')?0:1),
right:((navigator.product == 'Gecko')?2:2),
middle:((navigator.product == 'Gecko')?1:4)
}
var MouseState = {
//
// keeps up to date information about the mouse positions and the clickity click of its buttons.
// watching the mouse move event is pretty intense - resource wise - so turn it off when you
// aren't using it.
//
x: 0,
y: 0,
leftButtonDown: false,
rightButtonDown: false,
middleButtonDown: false,
onmousedown: function(e)
{
if (!e) var e = window.event
MouseState.leftButtonDown = (e.button & buttons.left)?true:false;
MouseState.rightButtonDown = (e.button & buttons.right)?true:false;
MouseState.middleButtonDown = (e.button & buttons.middle)?true:false;
},
onmouseup: function(e)
{
if (!e) var e = window.event
MouseState.leftButtonDown = (e.button & buttons.left)?false:MouseState.leftButtonDown;
MouseState.rightButtonDown = (e.button & buttons.right)?false:MouseState.rightButtonDown;
MouseState.middleButtonDown = (e.button & buttons.middle)?false:MouseState.middleButtonDown;
},
onmousemove: function(e)
{
if (!e) var e = window.event;
var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body
var dsocleft=document.all? iebody.scrollLeft : pageXOffset
var dsoctop=document.all? iebody.scrollTop : pageYOffset
MouseState.x = e.clientX + dsocleft;
MouseState.y = e.clientY + dsoctop;
},
captureMove: function(){
eventObserve(document, 'mousemove', MouseState.onmousemove);
},
releaseMove: function(){
eventStopObserving(document, 'mousemove', MouseState.onmousemove);
}
}
eventObserve(document, 'mousedown', MouseState.onmousedown);
eventObserve(document, 'mouseup', MouseState.onmouseup);

Comentarios»

No comments yet — be the first.

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s

A %d blogueros les gusta esto: