Javascript code snippets

Started by Darren Dirt, October 05, 2006, 11:38:50 AM

Previous topic - Next topic

Darren Dirt

Hey folks, a lot of us are web developers to some degree, and often there's a need to do the same simple task in project after project...

So I thought it would be nice to have a single thread here where you might place your little handydandy code library type of functions that you've painstakingly put together (simple stuff, not complex multi-method objects etc.) that you use all the time and/or that would reduce the need to search online to see "how other people have done it". :)


I'll start:

Javascript function "getDateText" (497 bytes)

//dt defaults to today if missing or not a valid date;
//i=1 means return "Thu 05Oct2006" otherwise "Thursday, October 05, 2006"

function getDateText(dt,i)
{
if(!dt||!dt.getYear||isNaN(dt.getYear()))dt=new Date();
var sy=dt.getYear();if(sy<1000)sy+=1900;
var sd=dt.getDate();if(sd<10)sd="0"+sd;
var ad="Sun,Mon,Tues,Wednes,Thurs,Fri,Satur".split(",");
var am="January,February,March,April,May,June,July,August,September,October,November,December".split(",");
return(1*i==1)?(ad[dt.getDay()].substring(0,3)+" "+sd+am[dt.getMonth()].substring(0,3)+sy):(ad[dt.getDay()]+"day, "+am[dt.getMonth()]+" "+sd+", "+sy);
};


So now, maybe in the future if you need to do a "document.write" directly to a welcome page, or you want to include the date in an alert() or an HTML report heading or something, you won't have to reinvent the wheel. :)


Also, this is handy when you want to "pad" a number with zeros, or add spaces to the beginning of a text (maybe to line up some columns or something)...

Javascript function "padChars" (142 bytes)

//s=original string;
//ch defaults to "0" if missing;
//i=minimum length of returned string, prefixed (padded) with "ch"
//e.g. ("123",5,".") returns "..123" ; ("123456",5,".") returns "123456" ; ("123",5) returns "00123"

function padChars(s,i,ch)
{
if(!s||!i)return s?s:"";
ch=ch?(""+ch).charAt(0):"0";
s=""+s;
while(s.length<i){s=ch+s;};
return s;
};

_____________________

Strive for progress. Not perfection.
_____________________

Darren Dirt

#1
Do you you want to prevent people from copying your Oh So Important content into the clipboard?

It's not exactly something I recommend trying to do (to me it's just as annoying as the right-click disablers -- an annoyance, and not really "protecting" anything because of view-source ... but I guess it stops the AOLers from "stealing" your stuff) but if you want the absolute most simple way, check this out... and as a "bonus" it is not wrapped inside <script>...</script> tags, so if someone is "stripping out" the script from your Oh So Important webpage, this select-preventer will still be working ;D


<body onselectstart="return false" ondragstart="return false" ...>



- - -

Oh, wait... what do I mean by "stripping out" script? Now *that* is an actually useful function (especially if you frequently save local copies of webpages and want to disable their redirects, frameset-forcers, trackers, bannerad-creators, etc.) ... here ya go!

Javascript function "removeScript" (244 bytes)

function removeScript(s)
{
//fix line endings
var r=s.replace(/[ \t]*?\r\n|\n|\r|\f/g,"\n");

var g=/(\<)script\b(.|\n)*?(\>)\s*?((\<)\!\-\-)?(.|\n)*?(\-\-(\>))?\s*?(\<)\/script\b(.|\n)*?(\>)\n?/gi;
while(r.match(g)){r=r.replace(g , "");};
return r;
};

:)
_____________________

Strive for progress. Not perfection.
_____________________

Darren Dirt

#2
Is your script (or someone else's) taking forever to run, and you get the annoying "unresponsive script/not responding" popup?

Here's how to increase the duration before you see that often-annoying message (that requires you to click Cancel or OK)...


- - -


Internet Explorer's secret "MaxScriptStatements" registry key
[HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Styles]
"MaxScriptStatements"=dword:004C4B40

^ that's what the DEFAULT is -- 5 million executed commands. Might take 15-30 seconds, depending on what code you're executing.

(personally, I set it to 02feeded -- which is about 50 million, and an easy hex value to "remember" :) )


- - -


Put off Firefox 1_5's Unresponsive script dialogue - a tip by Lifehacker
http://www.lifehacker.com/software/firefox/put-off-firefox-15s-unresponsive-script-dialogue-162574.php

Quote

One of the "features" of Firefox 1.5 is a pop-up dialog that appears whenever a page takes too long to load that reads, "Warning: Unresponsive script. A script on this page may be busy, or it may have stopped responding. You can stop the script now, or you can continue to see if the script will complete."

To which I ask, "Why, Mozilla? Why?" I run into this error a lot since I upgraded to Firefox 1.5, especially with the slow-as-snails installation of MovableType we wrestle with each day to publish Lifehacker. Happily it's not hard to delay this annoying dialog. To do so:

- Type about:config in Firefox's address bar.

- Filter down to the value for dom.max_script_run_time.

- Change the value to something higher than the default (which is 5, or is it 15?.) I set mine to 20 (180 would be 3 minutes).

- Bask in interruptionless browsing!


A comment by "Real Aler", in response to the above tip from lifehacker, might be useful too:
"Great tip. You can find most of the other possible changes using about:config on this page - http://kb.mozillazine.org/Firefox_:_FAQs_:_About:config_Entries " -- Darren's note: see also http://kb.mozillazine.org/Category:Preferences )


- - -

Enjoy your sanity. ;D
_____________________

Strive for progress. Not perfection.
_____________________

Mr. Analog

Y'know it's possible to write JavaScript with your own custom garbage collector. The current edition of "Javascript in a Nutshell" published by O'Reilly has some sample techniques.

Mind you that only helps with your own code, not some other moron...
By Grabthar's Hammer

Darren Dirt

#4
Sure garbage collection is A Good Idea, but sometimes a script truly does need to take more than the 10-15 seconds that are the default in IE and Mozilla, and it's not because of inefficient creation of objects and variables. ;D


Most of the time long-running scripts, that I have written or encountered, do so as a result of processing a lot of data and/or a lot of permutations of variable values (often because JS is being used as a quick proof-of-concept logic tool instead of a more difficult, but efficient, compiled language like C) so there *are* times when you want to disable/extend the "script timeout warning" duration. :)

An example of mine today: I have been doing some of my own "number crunching" to check out some statistics re. the odds of flopping or turn/rivering a straight based on certain often-quoted Texas Hold'em pocket combinations -- and since 50*49*48 = 117600 combinations, that means the pretty-efficient-considering-it's-Javascript functions I am calling will be called 117,600 times; rather time consuming ;) (Interestingly, and it should have been obvious but now I know "experimentally', but holding pocket54 will catch a straight *WAY* more often than the uber-powerful monster AK.)
_____________________

Strive for progress. Not perfection.
_____________________

Mr. Analog

I was able to write flexible enough javascript to process 300+ page contracts output in XML with the MSXML 3.0 parser for IE and render it in a series of spans with custom event handlers for each one.

JavaScript is capable of some fairly high CPU stuff without spilling out of the little box most browsers put it in. It's all about knowing the limits of what you can do with script and managing memory.
By Grabthar's Hammer

Darren Dirt

#6
On the subject of programming languages that, although not necessarily "the best", they actually do what most people need them to do... Here's a very thought-provoking article by Paul Graham: What makes a programming language "popular"? I especially like his observations about hackability ;D -- and if you're pressed for time, at least skim the final section ("12 The Dream Language")

_____________________

Strive for progress. Not perfection.
_____________________