viernes, 29 de junio de 2012

Disable HTML elements programatically

They asked me to disable / disable some html elements in the client side with javascript so the user cannot interact with cerrtain parts of an html document at some point. My sollution, based on jquery, is to put an html element in front of each elments we want to disable. This mask should be transparent and positioned absolutely with a big z-index. The following is an HTML document that demonstrates the problem and contains a simple implementation of a sollution. Hope it can be usefull to somebody needing something similar.

< !doctype html>
< html lang="es-UY">

< head>
< script src="" type="text/javascript">< /script>
< title>test< /title>
< /head>

< script type="text/javascript">
var lib = {
idCounter: 0, 
disablers: [], 
 * disable the given html elements by putting a mask html element with the same bounds in front of each given element. use disablers.enable for enabling them programatically. 
 * @param el - a reference to the elements to disable. For example, ".c1" will disable all elements of CSS class c1, "#el1" will disable the element id el1.
 * @param maskCSS - optional - an object with extra CSS value for the mask, for example: {"background-color": "red", opacity: 0.2}
 * @return the masks elements (array of jquery object) created
disable: function(el, maskCSS) {
 var masks = []; 
  masks.push(lib.disableOne(el, maskCSS)); 
 return masks; 
 * the same as disable, but treat the given object as a single element 
disableOne: function(el, maskCSS) {
 var id = $(el).attr("id"); 
 if(!id) {
  $(el).attr({"id": id}); 
 if(!lib.disablers[id]) {
  var dis = document.createElement("div"); 
 var dis = lib.disablers[id];
  "position": "absolute", "z-index": 99999, "display": 
  "block", "left": $(el).offset().left, "top": $(el).offset().top, 
  "width": $(el).width(), "height": $(el).height(), "opacity": 0.4, "background-color": "black"
 return dis; 
enable: function(el) {
 if($(el).attr("id") & & lib.disablers[$(el).attr("id")]) {
  var dis = lib.disablers[$(el).attr("id")]; 
< /script>

< p>The following table contains a disabled element< /p>

< table>
< tr>< td id="el1">< button>hello< /button>< /td>< td>< p>alskjdlaksjd< /p>< /td>< /tr>
< tr>< td>< button onclick="window.disabler.enable('#el1')">click me for enable < /button>< /td>< td>< p>als< a href="">kjdlaksj< /a>d< /p>< /td>< /tr>
< /table>

< script type="text/javascript">

//disable a single element with id "el1"

//disable all < a> elements: 
< /script>

< /body>

< /html>

No hay comentarios: