Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 38 total  RSS 

striphtml prototype function

striphtml prototype function

usage: $('elem').innerHTML.stripHTML();

   1  
   2  String.prototype.stripHTML = function() {
   3      var matchTag = /<(?:.|\s)*?>/g;
   4      return this.replace(matchTag, "");
   5  };

determine screen height

// description of your code here

..normally

   1  
   2  var h = document.documentElement.scrollHeight;


..however in some cases (safari 3) you may have to find where something is on the screen and generate the actual screen size around that
   1  
   2  if (($('lightbox_bottom').cumulativeOffset().top+30) > document.documentElement.scrollHeight) {
   3    $('sBg').style.height=$('lightbox_bottom').cumulativeOffset().top+30+'px';
   4  }
   5  else {
   6    $('sBg').style.height=document.documentElement.scrollHeight+'px';
   7  }


30 being the height of the bottom element your using to judge.

parent.subclasses is undefined - prototype 1.8.0 error

http://prototype.lighthouseapp.com/projects/8886/tickets/151-extending-yui-objects-with-prototype

fix

   1  
   2  Class.create = Class.create.wrap(function(proceed, parent) {
   3    if (Object.isFunction(parent))
   4      parent.subclasses = parent.subclasses || [];
   5    return proceed.apply(Class, $A(arguments).slice(1));
   6  })

Cursor object for easily changing cursor based on an event.

Uses the prototype.js library version 1.6. Prior to this version to access the "event" you must use Event.element(event).

Cursor Object with event driven functions to quickly change the cursor based on an event.

   1  
   2  <html>
   3  <head>
   4      <script type="text/javascript" src="/path/to/prototype.js"></script>
   5      <script type="text/javascript">
   6  
   7          var Cursor = {
   8              pointer:function(event){
   9                  //Event.element(event)  *** Prior to prototype 1.6 ***
  10                  event.element().setStyle({cursor:"pointer"});
  11              },
  12          
  13              normal:function(event){
  14                  event.element().setStyle({cursor:"crosshair"});
  15              },
  16          
  17              auto:function(event){
  18                  event.element().setStyle({cursor:"auto"});
  19              },
  20          
  21              crosshair:function(event){
  22                  event.element().setStyle({cursor:"crosshair"});
  23              },
  24          
  25              move:function(event){
  26                  event.element().setStyle({cursor:"move"});
  27              },
  28          
  29              e_resize:function(event){
  30                  event.element().setStyle({cursor:"e-resize"});
  31              },
  32          
  33              ne_resize:function(event){
  34                  event.element().setStyle({cursor:"ne-resize"});
  35              },
  36          
  37              n_resize:function(event){
  38                  event.element().setStyle({cursor:"n-resize"});
  39              },
  40          
  41              se_resize:function(event){
  42                  event.element().setStyle({cursor:"se-resize"});
  43              },
  44          
  45              sw_resize:function(event){
  46                  event.element().setStyle({cursor:"sw-resize"});
  47              },
  48          
  49              s_resize:function(event){
  50                  event.element().setStyle({cursor:"s-resize"});
  51              },
  52          
  53              w_resize:function(event){
  54                  event.element().setStyle({cursor:"w-resize"});
  55              },
  56          
  57              text:function(event){
  58                  event.element().setStyle({cursor:"text"});
  59              },
  60          
  61              wait:function(event){
  62                  event.element().setStyle({cursor:"wait"});
  63              },
  64          
  65              help:function(event){
  66                  event.element().setStyle({cursor:"help"});
  67              },
  68          
  69              progress:function(event){
  70                  event.element().setStyle({cursor:"progress"});
  71              }
  72          }
  73  
  74          Event.observe(window, "load", function(){
  75              $("example").observe("mouseover", Cursor.pointer.bindAsEventListener(Cursor));
  76  
  77              //Could also be:
  78              $("example").observe("mouseover", function(event){
  79                  Cursor.pointer(event);
  80              });
  81          });
  82      </script>
  83  <body>
  84      <div id="example">Cursor should switch from arrow to "Pointer" on mouseover</div>
  85  </body>
  86  </html>
  87  

Javascript Footnote Creator

Finds footnotes and adds them to a list. Just put "footnote" into the class of an element, and it'll automatically pull it out of context, replace it with a reference link, put the footnote into the list with id 'notes', and include a backreference so that your readers don't get lost. Embedded markup and nested footnotes work fine. Everything has CSS classes, so you can style it to your heart's content.

   1  
   2  		<script src='prototype.js'>
   3  			/*don't confuse IE; put content in empty script blocks*/
   4  		</script>
   5  		<script>
   6  			var Footnote = Class.create({
   7  				initialize: function(element) {
   8  					var notes = this.findNotes();
   9  					var number = notes.select('li').length + 1;
  10  					
  11  					var ref = document.createElement('a');
  12  					ref.className = 'footnote-reference';
  13  					ref.href = '#footnote-' + number;
  14  					ref.id = 'reference-' + number;
  15  					ref.appendChild(document.createTextNode(number));
  16  					element.parentNode.insertBefore(ref, element);
  17  					
  18  					$(element).removeClassName('footnote')
  19  					
  20  					var li = document.createElement('li');
  21  					li.className = 'footnote';
  22  					li.id = 'footnote-' + number;
  23  					li.appendChild(element);
  24  					
  25  					var backref = document.createElement('a');
  26  					backref.className = 'footnote-backreference';
  27  					backref.href = '#reference-' + number;
  28  					backref.appendChild(document.createTextNode("\u21A9"));
  29  					li.appendChild(document.createTextNode(" "));
  30  					li.appendChild(backref)
  31  					
  32  					notes.appendChild(li);
  33  				},
  34  				findNotes: function() {
  35  					return $('notes');
  36  				}
  37  			});
  38  			
  39  			Event.observe(window, 'load', function() {
  40  				$$('.footnote').each(function(e) {new Footnote(e)});
  41  			})
  42  		</script>

DIV instead SELECT tag

Unable to use CSS for select tag?
Simple changes approve it.

Use prototype framework

   1  
   2  <html>
   3     <head>
   4       <script type='text/javascript' src='js/prototype.js'></script>
   5       <script type='text/javascript'>
   6          function change_country(type, value) {
   7             $('country_type').value=type;
   8             $('country_value').value=value;
   9          }
  10       </script>
  11       <style type="text/css">		
  12          #select_countries {
  13             border: 1px solid #333;
  14             margin-top: 5px;
  15             height: 200px;
  16             width: 200px;
  17             overflow: auto;
  18          }
  19       </style>
  20     </head>
  21  <body>
  22  <form action="" method="post">
  23     <fieldset>
  24        <legend>Countries</legend>
  25        <input type="text" name="country_value" id="country_value" value="United States" />
  26        <input type="hidden" name="country_type" id="country_type" value="us" />
  27        <a href="#" onclick="Element.show('select_countries'); return false;">Click to change</a><br />
  28        <div id="select_countries" style="display: none;">
  29           <div id="close" onclick="Element.hide('select_countries'); return false;">Close</div>
  30           <div onclick="change_country('us', 'United states')"><img src="images/flags/us.gif" alt="us" /> United states</div>
  31           <div onclick="change_country('ru', 'Russia')"><img src="images/flags/ru.gif" alt="us" /> Russia</div>
  32           <div onclick="change_country('es', 'Spain')"><img src="images/flags/es.gif" alt="us" /> Spain</div>
  33           <div onclick="change_country('ca', 'Canada')"><img src="images/flags/ca.gif" alt="ca" /> Canada</div>
  34        </div>
  35     </fieldset>
  36  </form>
  37  </body>
  38  </html>

Rails-like number_to_currency currency formatting

This is pretty much a port of the Ruby on Rails number_to_currency method, right down to the hashed options.

   1  
   2  number_to_currency: function (number, options) {
   3    try {
   4      var options   = options || {};
   5      var precision = options["precision"] || 2;
   6      var unit      = options["unit"] || "$";
   7      var separator = precision > 0 ? options["separator"] || "." : "";
   8      var delimiter = options["delimiter"] || ",";
   9    
  10      var parts = parseFloat(number).toFixed(precision).split('.');
  11      return unit + reports.number_with_delimiter(parts[0], delimiter) + separator + parts[1].toString();
  12    } catch(e) {
  13      return number
  14    }
  15  },
  16  
  17  number_with_delimiter: function (number, delimiter, separator) {
  18    try {
  19      var delimiter = delimiter || ",";
  20      var separator = separator || ".";
  21      
  22      var parts = number.toString().split('.');
  23      parts[0] = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + delimiter);
  24      return parts.join(separator);
  25    } catch(e) {
  26      return number
  27    }
  28  }

Mac Menu effect js

Here the html code

   1  
   2  <html>
   3  <head>
   4  <title>JS</title>
   5  <script src="js/prototype.js" type="text/javascript"></script>
   6  <script src="fisheye_new_2.js" type="text/javascript"></script>
   7  <style>
   8  #menuBar{ width: 100%; text-align: center; position: relative; }
   9  #menuitems { text-align: center; margin-left: auto; margin-right: auto; width: 200px; }
  10  .menuitem { vertical-align: top; display: inline; background-color: #f00; }
  11  .menuitem img { vertical-align: top; width: 20px; height: 20px; border: 0px; }
  12  #logDiv { font-size: 10px; }
  13  </style>
  14  </head>
  15  <body>
  16  	<div id="menubar">
  17  		<div id="menuitems">
  18  			<div class="menuitem"><img onclick="alert(this.id);" src="test2.jpg" id="img1"></div>
  19  			<div class="menuitem"><img onclick="alert(this.id);" src="test2.jpg" id="img2"></div>
  20  			<div class="menuitem"><img onclick="alert(this.id);" src="test2.jpg" id="img3"></div>
  21  			<div class="menuitem"><img onclick="alert(this.id);" src="test2.jpg" id="img4"></div>
  22  			<div class="menuitem"><img onclick="alert(this.id);" src="test2.jpg" id="img5"></div>
  23  			<div class="menuitem"><img onclick="alert(this.id);" src="test2.jpg" id="img6"></div>
  24  		</div>
  25  	</div>
  26  	<div id="position"></div>
  27  	<div id="logDiv"></div>
  28  </body>
  29  </html>


and the javascript, require prototypejs
   1  
   2  var maxDist = 0;
   3  
   4  function mousemove(e) {
   5  	var eX = Position.page($('menuitems'))[0];
   6  	var eY = Position.page($('menuitems'))[1];
   7  	var eWidth = parseInt($('menuitems').getStyle('width'));
   8  	var pX = Event.pointerX(e);
   9  	var pY = Event.pointerY(e);
  10  	var imgs = $('menuitems').immediateDescendants();
  11  	for (var i = 0; i < imgs.length; i++) {
  12  		var distFromMouse = calcDistFromMouse(pX, pY, imgs[i].firstDescendant());
  13  		if (distFromMouse < 45) {
  14  			var newSize = parseInt(distFromMouse * (-0.4) + 50);
  15  			imgs[i].firstDescendant().setStyle({ width: newSize, height: newSize});
  16  		} else {
  17  			imgs[i].firstDescendant().setStyle({ width: 20, height: 20});
  18  		}
  19  	}
  20  }
  21  
  22  function resetScaling () {
  23  	var imgs = $('menuitems').immediateDescendants();
  24  	for (var i = 0; i < imgs.length; i++) {
  25  		var newSize = 20;
  26  		imgs[i].setStyle({ width: newSize, height: newSize});
  27  	}
  28  }
  29  
  30  function calcDistFromMouse(mX, mY, elem) {
  31  	var elemCenterX = parseInt(Position.page(elem)[0]) + (parseInt(elem.getStyle('width')) / 2);
  32  	var elemCenterY = parseInt(Position.page(elem)[1]) + (parseInt(elem.getStyle('height')) / 2);
  33  	var distance = parseInt(Math.sqrt((elemCenterX - mX) * (elemCenterX - mX) + (elemCenterY - mY) * (elemCenterY - mY)));
  34  	return distance;
  35  }
  36  
  37  function checkMousePos(pX, pY, eX, eY, eWidth ){
  38  	if (pY - eY > 200)
  39  		return false;
  40  	if (pX > eX) {
  41  		if (pX - (eX + eWidth) > 200)
  42  			return false;
  43  	} else {
  44  		if (eX - pX > 200)
  45  			return false;
  46  	}
  47  	return true;
  48  }
  49  
  50  Event.observe(window,'load', function() {
  51    Event.observe(document,'mousemove',mousemove, false);
  52  });

Javascript Array Intersect

Simple intersect function

   1  
   2  Object.extend(Array.prototype, {
   3    intersect: function(array){
   4      return this.findAll( function(token){ return array.include(token) } );
   5    }
   6  });

Selezione di elementi JS

   1  
   2  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   3          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   5  <head>
   6    <title>Prova di selezione rettangolo</title>
   7    <script src="http://www.prototypejs.org/javascripts/prototype.js" type="text/javascript"></script>
   8    
   9    <script>
  10    
  11  	Event.observe(window, 'load',function() {
  12  	
  13  		Event.observe(document, 'mousedown', MyDragger.OnMouseDown);
  14  		Event.observe(document, 'mouseup', MyDragger.OnMouseUp);
  15  		Event.observe(document, 'mousemove', MyDragger.OnMouseMove);
  16  	});
  17    
  18  		// cevrond 2007.05.11
  19    
  20    var MyDragger = window.MyDragger || {};
  21    
  22    MyDragger.PointClick = { x: -1, y: -1 };
  23    MyDragger.Status = -1; // -1: not dragging, 0: clicked, 1: dragging
  24    MyDragger.Targets = [];
  25  
  26    MyDragger.OnMouseDown = function(e) {
  27  
  28  		MyDragger.Log('mouse', 'mousedown');
  29  
  30  		MyDragger.PointClick.x = Event.pointerX(e);
  31  		MyDragger.PointClick.y = Event.pointerY(e);
  32  
  33  		MyDragger.SetBox(MyDragger.PointClick.x, MyDragger.PointClick.y, -1, -1);
  34  		MyDragger.Status = 0;
  35  		
  36  		var els = $$('div.pippo');
  37  		for (var i = 0, m = els.length ; i < m; i++) {
  38  
  39  			var el = els[i];
  40  
  41  			MyDragger.ElUnselect(el);
  42  
  43  			var xy = Position.cumulativeOffset(el);
  44  			var wh = el.getDimensions();
  45  			
  46  			var t = { el: el, l: xy[0], t: xy[1], r: xy[0] + wh.width, b: xy[1] + wh.height, hl: false};
  47  
  48  			MyDragger.Targets[ MyDragger.Targets.length ] = t;
  49  		}
  50  
  51  		return false;
  52  	}
  53  
  54    MyDragger.OnMouseUp = function(e) {
  55    
  56  		MyDragger.Log('mouse', 'mouseup');
  57  
  58  		MyDragger.Status = -1;
  59  		MyDragger.Targets = [];
  60  
  61  		return false;
  62  	}
  63  
  64    MyDragger.OnMouseMove = function(e) {
  65    
  66  		var x = Event.pointerX(e);
  67  		var y = Event.pointerY(e);
  68  
  69  		MyDragger.Log('pointer', "X1: " + MyDragger.PointClick.x + " -- X2: " + x + " -- Y1: " + MyDragger.PointClick.y + " -- Y2: " + y);
  70  
  71  		var cw = Math.abs(MyDragger.PointClick.x - x);
  72  		var ch = Math.abs(MyDragger.PointClick.y - y);
  73  
  74  			// evita di cominciare la selezione se non si รจ mosso di almeno 2px
  75  
  76  		if (MyDragger.Status === 0 && (cw > 2 || ch > 2))
  77  			MyDragger.Status = 1;
  78  
  79  		if (MyDragger.Status === 1) {
  80  	
  81  			var cl = Math.min(MyDragger.PointClick.x, x);
  82  			var ct = Math.min(MyDragger.PointClick.y, y);
  83  
  84  			MyDragger.SetBox(ct, cl, cw, ch);
  85  
  86  			var cb = ct + ch;
  87  			var cr = cl + cw;
  88  
  89  			for (var i = 0, m = MyDragger.Targets.length; i < m; i++) {
  90  			
  91  				var d = MyDragger.Targets[i];
  92  			
  93  				((cl > d.r || cr < d.l || ct > d.b || cb < d.t) ? MyDragger.ElUnselect : MyDragger.ElSelect)(d.el);
  94  			}
  95  		}
  96  		
  97  		return false;
  98  	}
  99  
 100  		// interazione con gli elementi
 101  
 102  	MyDragger.ElSelect = function(el) {
 103  
 104  		el.setStyle({backgroundColor:'red'});
 105  	}
 106  
 107  	MyDragger.ElUnselect = function(el) {
 108  
 109  		el.setStyle({backgroundColor:'transparent'});
 110  	}
 111  	
 112  		// interazione col box di selezione
 113  
 114  	MyDragger.SetBox = function(t, l, w, h) {
 115  
 116  		var box = $('box');
 117  		
 118  		if (w === -1 || h === -1)
 119  			box.setStyle({ display: 'none' });
 120  		else
 121  		box.setStyle({
 122  			display: '',
 123  			top: t + 'px',
 124  			left: l + 'px',
 125  			width: w + 'px',
 126  			height: h + 'px'
 127  		});
 128  	}
 129  
 130  		// per un po' di logging ...
 131  
 132    MyDragger.Log = function(where, what) {
 133    
 134  		$(where).innerHTML = what;
 135  	}
 136  
 137    </script>
 138  </head>
 139  <body>
 140  <div id="debug_container" style="border: 1px red solid">
 141  	<div id="mouse"></div>
 142  	<div id="pointer"></div>
 143  	<div id="pippoc"></div>
 144  	<div id="rectc"></div>
 145  </div>
 146  
 147  <div id="box" style="border: 1px green solid; position: absolute;z-Index: 1000"></div>
 148  
 149  <div id="pippo" class="pippo" style="position:absolute;left:200px;top:200px;width:100px;height:100px;border: 2px blue solid" onclick="pippoClick(this)"></div>
 150  <div id="pippo2" class="pippo" style="position:absolute;left:300px;top:200px;width:100px;height:100px;border: 2px blue solid" onclick="pippoClick(this)"></div>
 151  <div id="pippo3" class="pippo" style="position:absolute;left:400px;top:200px;width:100px;height:100px;border: 2px blue solid" onclick="pippoClick(this)"></div>
 152  
 153  </body>
 154  </html>
« Newer Snippets
Older Snippets »
Showing 1-10 of 38 total  RSS