5 Replies - 724 Views - Last Post: 15 December 2012 - 07:05 PM

#1 BetaWar  Icon User is offline

  • #include "soul.h"
  • member icon

Reputation: 1183
  • View blog
  • Posts: 7,254
  • Joined: 07-September 06

Javascript gems - Post yours

Posted 12 December 2012 - 03:32 PM

There are tons of cute little things you can accomplish with a scripting language like Javascript. Recently I was trying to determine if there was a way to send functions to and from the server as a JSON string and make use of them (on the client side). With a little messing around the answer is most certainly a "yes". Here's how:

// First, create your object to be stringified
var j = {
  dat: [123, 456, 789],
  cb: function(){
    alert("test");
  }
};

// Then stringify it, with a slight modification
var s = JSON.stringify(j, function(key, val){
  // when we find a function, we need to make it a string
  if(typeof(val) == "function"){
    return "" + val;
  }
  return val;
});
//console.log(s);

// To get the function back, parse the JSON with a slight modification
var loaded = JSON.parse(s, function(key, val){
  // If we can match what a general function looks like
  if(("" + val).match(/^function[ ]?\(\){([^\0]*)?}$/)){
    // return the evaluated form of the function
    return eval("(" + val + ")");
  }
  return val;
});
// And now you can call it.
//console.log(loaded.cb);
loaded.cb();



So, what gems do you have in relation to Javascript?

Is This A Good Question/Topic? 4
  • +

Replies To: Javascript gems - Post yours

#2 e_i_pi  Icon User is offline

  • = -1
  • member icon

Reputation: 800
  • View blog
  • Posts: 1,686
  • Joined: 30-January 09

Re: Javascript gems - Post yours

Posted 12 December 2012 - 05:42 PM

I wrote a small jQuery plugin for highlighting invalid fields in forms. Currently I have the invalidation code on click events (so that diverse validation rules can be applied), but it could easily be moved to the plugin with a mode declaration on the function call:
<head>
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
	<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
</head>
<body>
	<form>
		<label>Non-empty field</label>
		<input id="nonEmptyField">
		<input id="formSubmit" type="submit" value="Click!">
	</form>
	<script type="text/javascript">
		$(document).ready(function() {
			// The plugin
			(function($){
				$.fn.highlightInvalidField = function() {  
					return this.each(function() {
						var highlightColor = '#df6a0b';
						var $this = $(this);
						var originalColor = $this.css('background-color');
						$this.animate({backgroundColor: highlightColor}, 125);
						$this.animate({backgroundColor: originalColor}, 1000);

					});
				};
			})(jQuery);
			
			// Calling the plugin
			$('#formSubmit').off('click').on('click', function() {
				if($('#nonEmptyField').val() == '')
				{
					$('#nonEmptyField').highlightInvalidField();
					return false;
				}
			});
		});
	</script>
</body>

This post has been edited by e_i_pi: 12 December 2012 - 05:43 PM

Was This Post Helpful? 1
  • +
  • -

#3 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3569
  • View blog
  • Posts: 10,403
  • Joined: 08-June 10

Re: Javascript gems - Post yours

Posted 12 December 2012 - 07:19 PM

not a really small script, however a nice game: Image Slider with arbitrary size: http://bytes.kulturb...ageSlider.xhtml
Was This Post Helpful? 1
  • +
  • -

#4 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3729
  • View blog
  • Posts: 13,024
  • Joined: 12-December 12

Re: Javascript gems - Post yours

Posted 15 December 2012 - 06:38 PM

There are a number of Date.format() methods but they don't distinguish between (or enable) am/pm and AM/PM, have an option to use a 12-hour clock, include milliseconds, or are able to insert suffixes (12th, 3rd):

Date.prototype.format = function (sFormat, twelve) {
    // Returns: A string version of the date.
    // Usage: date_instance.format("d mmm yy hh:nn:ss ap") or 
    // date_instance.format("dddd dd mmmm hh:nn", true)
    // Defaults to YYYY/MM/DD.
    // twelve == true for a 12hr clock, or just AP or ap within 
    // sFormat (for AM/PM or am/pm).
    // Use z or zzz for milliseconds and xx for suffixes (st, nd, etc.).
    var MonthNames = ["January", "February", "March", "April", "May", "June", 
        "July", "August", "September", "October", "November", "December"];
    var DayNames = [ "Sunday", "Monday", "Tueday", "Wednesday", "Thursday", 
        "Friday", "Saturday" ];
    var dDate = this || new Date(),
        D = dDate.getDate(), DDDD = DayNames[dDate.getDay()], 
        DDD = DDDD.substr(0,3),
        M = dDate.getMonth()+1, MMMM = MonthNames[dDate.getMonth()], 
        MMM = MMMM.substr(0,3),
        YYYY = dDate.getFullYear(), YY = ('' + YYYY).substr(2, 2),
        H = dDate.getHours(), N = dDate.getMinutes(), S = dDate.getSeconds(),
        Z = dDate.getMilliseconds(),
        ap = (H > 11) ? "pm" : "am",
        // pad with leading zeros, if required
        DD = ( D < 10 ? "0" : "" ) + D,
        MM = ( M < 10 ? "0" : "" ) + M,
        NN = ( N < 10 ? "0" : "" ) + N, 
        SS = ( S < 10 ? "0" : "" ) + S,
        ZZZ = ( Z < 10 ? "00" : (Z < 100 ? "0" : "") ) + Z, XX;
    var AP = (sFormat && (sFormat.toUpperCase().indexOf('AP')+1)) ? 
        ((sFormat.indexOf('ap')+1) ? ap : ap.toUpperCase()) : '';
    if (twelve || AP) {
        H = (H < 12) ? (H || 12) : ((H - 12) || 12);
    }
    var HH = ( H < 10 ? "0" : "" ) + H;
    XX = (D == 1 || D == 21 || D == 31) ? "st" : 
        ((D == 2 || D == 22) ? "nd" : ((D == 3 || D == 23) ? "rd" : "th"));
    sFormat = ( sFormat ) ? sFormat.toUpperCase() : 'YYYY/MM/DD';
    var sParsed = sFormat.replace(/D{1,4}|M{1,4}|Y{2,4}|H{1,2}|N{1,2}|S{1,2}|Z{1,3}|XX|AP/g,
        function (m) {
            try {
                return eval(m);
            } catch (e) {
                return '';
            }
        });
    return sParsed;
};

Was This Post Helpful? 1
  • +
  • -

#5 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3729
  • View blog
  • Posts: 13,024
  • Joined: 12-December 12

Re: Javascript gems - Post yours

Posted 15 December 2012 - 06:56 PM

Just one more: This is a bookmarklet that, when moving the mouse around a page, will display css details for elements, outlining them in red. The distinguishing feature is that you can click on elements to "fix" the information on the page. Pressing Escape will cancel the feature, and just refresh the page to remove.

To use: copy the code and create a new Bookmark (or Favorite). Paste the code as the URL or Address (depending on the browser).

javascript:(function(){var d=document,useMine=true,prevEl,info;function addHandler(orig,mine){return function(e){if(useMine){mine(e);}else if(orig){orig(e);}};}function GS(el,sRule){var result='';if(d.defaultView&&d.defaultView.getComputedStyle){result=d.defaultView.getComputedStyle(el,'').getPropertyValue(sRule);}else if(el.currentStyle){sRule=sRule.replace(/\-(\w)/g,function (strMatch,p1){return p1.toUpperCase();});result=el.currentStyle[sRule];}else{result='n/a';}return sRule+': '+result;}function myover(e){var el=e?e.target:window.event.srcElement;el.style.outline='1px solid red';var sInfo=el.nodeName;if(el.id)sInfo+=" ID: "+el.id;sInfo+="\n";if(el.className)sInfo+="Class: "+el.className+"\n";sInfo+=GS(el,'width')+" "+GS(el,'height');sInfo+="\n"+GS(el,'padding');sInfo+="\n"+GS(el,'border');sInfo+="\n"+GS(el,'margin');sInfo+="\n"+GS(el,'display');sInfo+="\n"+GS(el,'position');sInfo+="\n"+GS(el,'font');sInfo+="\n"+GS(el,'float');sInfo+=" "+GS(el,'z-index');info.value=sInfo;prevEl=el;}function myout(e){var el=e?e.target:window.event.srcElement;if(!el.keepOl)el.style.outline='';}function mymove(e){var evt=e||window.event;var el=evt.target||evt.srcElement;info.style.left=parseInt(evt.pageX)+20+"px";info.style.top=parseInt(evt.pageY)+10+"px";}function myclick(e){var evt=e||window.event;var el=evt.target||evt.srcElement;info.style.left=parseInt(evt.pageX)+4+"px";info.style.top=parseInt(evt.pageY)+4+"px";el.keepOl=true;createBox();if(el.href){var temp=el.href;el.href="#";window.setTimeout(function (){el.href=temp;},20);}evt.preventDefault;return false;}function mydown(e){var evt=e||window.event;if(evt.keyCode==27){if(!prevEl.keepOl)prevEl.style.outline='';useMine=false;info.parentNode.removeChild(info);}}function createBox(){info=d.createElement('textarea');info.style.position="absolute";info.style.width="250px";info.style.height="170px";info.style.zIndex="999";info.style.fontSize="11px";info.style.color="black";info.style.backgroundColor="lightyellow";info.style.paddingLeft="3px";d.body.appendChild(info);}d.onmouseover=addHandler(d.onmouseover,myover);d.onmouseout=addHandler(d.onmouseout,myout);d.onmousemove=addHandler(d.onmousemove,mymove);d.onclick=addHandler(d.onclick,myclick);d.onkeydown=addHandler(d.onkeydown,mydown);createBox();})()

Older browsers may not allow so many characters. If this happens for you let me know which browser you are using and I will endeavour to reduce the number of characters. Andy.

Attached image(s)

  • Attached Image

Was This Post Helpful? 1
  • +
  • -

#6 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3729
  • View blog
  • Posts: 13,024
  • Joined: 12-December 12

Re: Javascript gems - Post yours

Posted 15 December 2012 - 07:05 PM

Actually, follows a minified version. It could still be made smaller if necessary but I would likely need to reduce its functionality.

(function(){function i(e,n){return function(r){if(t){n(r)}else if(e){e(r)}}}function s(t,n){var r="";if(e.defaultView&&e.defaultView.getComputedStyle){r=e.defaultView.getComputedStyle(t,"").getPropertyValue(n)}else if(t.currentStyle){n=n.replace(/\-(\w)/g,function(e,t){return t.toUpperCase()});r=t.currentStyle[n]}else{r="n/a"}return n+": "+r}function o(e){var t=e?e.target:window.event.srcElement;t.style.outline="1px solid red";var i=t.nodeName;if(t.id)i+=" ID: "+t.id;i+="\n";if(t.className)i+="Class: "+t.className+"\n";i+=s(t,"width")+" "+s(t,"height");i+="\n"+s(t,"padding");i+="\n"+s(t,"border");i+="\n"+s(t,"margin");i+="\n"+s(t,"display");i+="\n"+s(t,"position");i+="\n"+s(t,"font");i+="\n"+s(t,"float");i+=" "+s(t,"z-index");r.value=i;n=t}function u(e){var t=e?e.target:window.event.srcElement;if(!t.keepOl)t.style.outline=""}function a(e){var t=e||window.event;var n=t.target||t.srcElement;r.style.left=parseInt(t.pageX)+20+"px";r.style.top=parseInt(t.pageY)+10+"px"}function f(e){var t=e||window.event;var n=t.target||t.srcElement;r.style.left=parseInt(t.pageX)+4+"px";r.style.top=parseInt(t.pageY)+4+"px";n.keepOl=true;c();if(n.href){var i=n.href;n.href="#";window.setTimeout(function(){n.href=i},20)}t.preventDefault;return false}function l(e){var i=e||window.event;if(i.keyCode==27){if(!n.keepOl)n.style.outline="";t=false;r.parentNode.removeChild(r)}}function c(){r=e.createElement("textarea");r.style.position="absolute";r.style.width="250px";r.style.height="170px";r.style.zIndex="999";r.style.fontSize="11px";r.style.color="black";r.style.backgroundColor="lightyellow";r.style.paddingLeft="3px";e.body.appendChild(r)}var e=document,t=true,n,r;e.onmouseover=i(e.onmouseover,o);e.onmouseout=i(e.onmouseout,u);e.onmousemove=i(e.onmousemove,a);e.onclick=i(e.onclick,f);e.onkeydown=i(e.onkeydown,l);c()})()

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1