PDA

View Full Version : Generally Useful Javascript Functions..Thread



Falkon303
10-10-2008, 01:41 AM
Hopefully this will be made a sticky someday, but I feel it'd be nice to start a thread of normal every day useful javascript functions that people forget sometimes (guilty).


This is a Basic Javascript Checkbox Validation script... They used to bug the crap out of me.



<input onclick="checkthebox();" type="checkbox" name="music" id="music" value="checkbox">
<script>
function checkthebox()
{if(document.getElementById('music').checked)
{alert('you checked it!');} else {alert('please check the checkbox');}}
</script>

Twey
10-10-2008, 02:16 AM
var Format = (function() {
function interpolate(s, o) {
s = s.replace(/\[\[/g, '\0');
for (var x in o)
if (o.hasOwnProperty(x))
s = s.replace(new RegExp('\\[' + x + '\\]', 'g'), o[x]);
return s;
}

return {
interpolate: interpolate
};
})();

var Functions = (function() {
var O = {
lookup: function(a, i) {
return a[i];
},

equals: function(a, b) {
return a === b;
}
};

var F = {
bind: function(obj, fun, args) {
return function() {
if (obj === true)
obj = this;

var f = typeof fun === "string" ? obj[fun] : fun;

return f.apply(obj, Array.prototype.slice.call(args || [])
.concat(Array.prototype.slice.call(arguments)));
};
},

compose: function(/* f1 [, f2 [, ... [, fn]]] */) {
var fs = Array.prototype.slice.call(arguments);

return function() {
var args = Array.prototype.slice.call(arguments);

for (var i = fs.length - 1; i >= 0; --i)
args.unshift(fs[i].apply(this, args));

return args[0];
};
},

reorder: function(f, ord) {
return function() {
var oldargs = Array.prototype.slice.call(arguments);

return f.apply(this, F.map(function(v) { return oldargs[v]; }, ord));
};
},

flip: function(f) {
return F.reorder(f, [1, 0]);
},

curry: function(f, l, a) {
l = (typeof l === "number" ? l : (f.length || 0));
a = a || [];

return function() {
var m = a.concat(Array.prototype.slice.call(arguments));
return m.length < l ? Functional.curry(f, l, m) : f.apply(this, m);
};
},

Operators: O
};

return F;
})();

var Lists = {
map: function(f, a) {
for (var i = a.length - 1, r = []; i >= 0; --i)
r[i] = f(a[i], i);

return r;
},

reduce: function(f, t, a) {
for (var i = 0, n = a.length; i < n; ++i)
t = f(t, a[i]);
return t;
},

filter: function(f, a) {
for (var i = 0, r = [], n = a.length; i < n; ++i)
if (f(a[i], i))
r[r.length] = a[i];

return r;
}
};

var using = (function() {
var extensions = {}, global = this;

function isApplied(extn) {
var e = extn.split('.');
return extensions[e[0]][e[1]] && global[e[0]].prototype[e[1]];
}

function apply(extn) {
var e = extn.split('.');
return global[e[0]].prototype[e[1]] = extensions[e[0]][e[1]];
}

function unapply(extn) {
var e = extn.split('.');
delete global[e[0]].prototype[e[1]];
}

function using() {
var extns = Array.prototype.slice.call(arguments);
return function(fn) {
return function() {
for (var i = extns.length; --i >= 0; )
if (!isApplied(extns[i]))
apply(extns[i]);
else
extns.splice(i, 1);

var r = fn.apply(this, Array.prototype.slice.call(arguments));

for (var i = extns.length; --i >= 0; )
unapply(extns[i]);

return r;
};
};
}

function add(c, o) {
for (var x in o)
if (o.hasOwnProperty(x))
(extensions[c] || (extensions[c] = {}))[x] = o[x];
return o;
}

function get() {
return extensions;
}

using.add = add;
using.get = get;

return using;
})();

var Generic = (function() {
var MATCH_FAIL = {},
MATCH_ANY = {};

function create(fallback) {
var s = function() {
for (var i = 0, args = Array.prototype.slice.call(arguments), r; i < specs.length; ++i)
if ((r = specs[i].match(args)) !== MATCH_FAIL)
return r;

if (s._fallback)
return s._fallback.apply(this, args);

throw new Error("Generic: No methods matched and no fallback provided.");
}, specs = s._specs = [];

s.specialise = specialise;
s.addFallback = addFallback;
if (fallback)
s.addFallback(fallback);

return s;
}

function specialise(patterns, func) {
var s = this._specs;

s[s.length] = new Specialisation(patterns, func, this);

return this;
}

function addFallback(func) {
this._fallback = func;

return this;
}

/**** Begin Specialisation ****/

function Specialisation(patterns, func, context) {
this.patterns = patterns;
this.func = func;
this.context = context;
}

Specialisation.compatible = function(value, pattern) {
if (pattern === MATCH_ANY && value !== undefined)
return true;
else if ((typeof pattern === "string" || pattern instanceof String) && typeof value === pattern)
return true;
else if ((typeof pattern === "function" || pattern instanceof Function) && value instanceof pattern)
return true;
else if (pattern instanceof Pattern)
return pattern.guard(value);
else if (pattern instanceof Interface)
return pattern.match(value);

return false;
};

Specialisation.prototype = {
match: function(args) {
for (var i = 0, a = this.patterns, n = a.length; i < n; ++i)
if (!Specialisation.compatible(args[i], a[i]))
return MATCH_FAIL;

return this.func.apply(this.context, args);
}
};

/**** Begin Pattern ****/

function Pattern(guard) {
this.guard = guard;
}

function GUARD(func) {
return new Pattern(func);
}

function GUARD_IS(right) {
return new Pattern(function(val) {
return val === right;
});
}

/**** Begin Interface ****/

function Interface(obj) {
if (!(this instanceof Interface))
return new Interface(obj);

for (var x in obj)
if (obj.hasOwnProperty(x))
this[x] = obj[x];
}

Interface.getSkeleton = function(obj) {
var r = {};

for (var x in obj)
if (obj.hasOwnProperty(x))
r[x] = typeof obj[x];

return new Interface(r);
};

Interface.prototype = {
match: function(value) {
for (var x in this)
if (this.hasOwnProperty(x) && !Specialisation.compatible(value[x], this[x]))
return false;

return true;
}
};

return {
create: create,
Interface: Interface,
GUARD: GUARD,
GUARD_IS: GUARD_IS,
MATCH_ANY: MATCH_ANY
};
})();I'm sure I could think of some more (noticeably, my zip() function is missing... anyone know where that got to?). I'd quite like to include my Javascript cells implementation, which is very handy, but is also, I think, on my other harddrive, which is in a defunct machine.

Falkon303
10-10-2008, 02:27 AM
This is a very short tabbed content script I came up with recently while dinkin around. It uses html colors, but is easily modifiable to support image change out if needed. Also supports a "default tab loaded" function. Small in size, which is nice. I'd like to see how small this script could be... could be fun. Looks like butt in Firefox right now too.


<head>
<style type="text/css">
.selecttabs{cursor:pointer;background-color:#cccccc;background-repeat:no-repeat;display:inline;width:96px;height:22px;margin-right:3px;text-align:center;}
.selectcontent{width:100%;border:1px solid #cccccc;padding:5px;height:300px;list-style-type:none;}
</style>
<script type="text/javascript">
function defload()
{
// Set the default tab you want loaded next line down.
Default_Tab_Loaded = '2';
calldef = document.getElementById(Default_Tab_Loaded);
document.getElementById(Default_Tab_Loaded).id = 'selected';document.getElementById('selected').style.backgroundColor = '#ffff00';
document.getElementById(calldef.title + '_content').style.display = '';document.getElementById('selected').id = Default_Tab_Loaded;
}
function tabber()
{var divs = document.frmMain.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++)
{if (divs[i].id=='selected')
{divs[i].style.backgroundColor = '#ffff00';document.getElementById(divs[i].title + '_content').style.display = '';}
else
{divs[i].style.backgroundColor = '#cccccc';document.getElementById(divs[i].title + '_content').style.display = 'none';}}}
</script>
</head>
<body onload="defload();">
<form style="margin-bottom:0px;" id="frmMain" name="frmMain">
<div class="selecttabs" onclick="this.id = 'selected';tabber();this.id='1'" id="1" name="1" title="hats"/>one</div>
<div class="selecttabs" onclick="this.id = 'selected';tabber();this.id='2'" id="2" name="2" title="shirts"/>two</div>
<div class="selecttabs" onclick="this.id = 'selected';tabber();this.id='3'" id="3" name="3" title="cars">three</div>
<div class="selecttabs" onclick="this.id = 'selected';tabber();this.id='4'" id="4" name="4" title="chess">four</div>

<ul style="width:400px;height:400px;list-style-type:none;margin:0px;">
<!-- Next down is where you have your content. -->
<li id="hats_content" style="display:none;" class="selectcontent">content1</li>
<li id="shirts_content" style="display:none;" class="selectcontent">shirts</li>
<li id="cars_content" style="display:none;" class="selectcontent">content3</li>
<li id="chess_content" style="display:none;" class="selectcontent">content4</li>
</ul>
</form>
</body>
</html>

Falkon303
10-10-2008, 08:56 AM
This is a simple way to get, and now set the vertical and horizontal scroll location of a div layer.



<body onload="document.getElementById('huh').scrollTop = '20';document.getElementById('huh').scrollLeft = '10';">
<div id="read" name="read"></div>
<div id="huh" name="huh" onmousemove="document.getElementById('read').innerHTML = 'y: ' + this.scrollTop + ' x: ' + this.scrollLeft;" style="width:300px;height:450px;overflow:auto;border:1px solid #cccccc;">
<img src="http://i2.photobucket.com/albums/y21/steviepot/cheeseburger_helmit.jpg">
</div>
</body>

jscheuer1
10-10-2008, 09:00 AM
var Format = (function() {
function interpolate(s, o) {
s = s.replace(/\[\[/g, '\0');
for (var x in o)
if (o.hasOwnProp . . .
. . . nterface,
GUARD: GUARD,
GUARD_IS: GUARD_IS,
MATCH_ANY: MATCH_ANY
};
})();I'm sure I could think of some more (noticeably, my zip() function is missing... anyone know where that got to?). I'd quite like to include my Javascript cells implementation, which is very handy, but is also, I think, on my other harddrive, which is in a defunct machine.

The prototwey.js library? Perhaps tweyQuery?

Twey
10-10-2008, 08:53 PM
Much smaller, no weird interdependencies :) Just a few handy functions.

I'm seeing a lot of bad code here, folks. Remember, innerHTML is proprietary, leads to bad design, and has some weird effects and bugs. Stay away from it — you can do anything you need to with the DOM methods, unless you're actually accepting HTML as input from the user (a pretty rare scenario). Also, don't forget to keep your code valid.

Falkon303
10-10-2008, 11:20 PM
Much smaller, no weird interdependencies :) Just a few handy functions.

I'm seeing a lot of bad code here, folks. Remember, innerHTML is proprietary, leads to bad design, and has some weird effects and bugs. Stay away from it you can do anything you need to with the DOM methods, unless you're actually accepting HTML as input from the user (a pretty rare scenario). Also, don't forget to keep your code valid.


Could you expand on this for me? I am interested, just unaware due to browsing and learning that way. I'd really appreciate it if you could provide me with a very basic example.

Twey
10-11-2008, 05:07 AM
http://dynamicdrive.com/forums/showpost.php?p=158839&postcount=1337 — 1.*, 3.1.

Falkon303
10-11-2008, 08:47 PM
Very useful.. I did some reading last night about this. Although the efficiency is a tiny bit hurt when using DOM, it seems that the compatibility and validation/standardization of the program is set in stone.

I read a few article on this, and the majority of people supported .innerHTML, although for enterprise/professional, it was DOM or bust.

I'll keep my mouth shut on useful script until I know the DOM, as to not mislead peeps. :)
Thanks for this..... further up the mountain we go! :D

What about the idea of creating an innerHTML to DOM conversion proggy?

Not for loading of course, but rather as a translator. Any thoughts?