Click to See Complete Forum and Search --> : Your Best Custom Functions


TJ111
11-06-2007, 03:59 PM
It seems I will write some function just being lazy, then every new project I have to go back and dig through some old stuff to find those functions again. In doing so, I got to thinking about what other people consider their must-have functions that make life so much easier for them.

Here are probably my favorite three out of the bunch.


function removeChildren(elem) {
if (!elem) {
return false;
}
if (!elem.hasChildNodes()) {
return true;
}
while (elem.hasChildNodes()) {
elem.removeChild(elem.firstChild);
}
return true;
}
function appendChildren(parent, kids) {
for (var i=0; i<kids.length; i++) {
parent.appendChild(kids[i]);
}
}

function mkTxt (elem, string) {
var x = document.createElement(elem);
var y = document.createTextNode(string);
x.appendChild(y);
return x;
}
////////
//Doesn't seem like much, but this is how it comes in handy.
///////
var div = document.getElementById("div");
var h2 = mkTxt("h2", "Page Title");
var p = mkTxt("p", "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla nec quam. Quisque est. Nunc tincidunt, sem quis accumsan tincidunt, leo ipsum ultrices quam, sed sodales eros elit non risus.");

appendChildren(div, [h2, p]);
removeChildren(div);


Whats your best/favorite/most necassary functions (any language)?

WebJoel
11-09-2007, 05:28 PM
I have no idea what this jewel does... but suspect what it might do. (I have really got to learn *php)

COMPUTERS and AIR CONDITIONERS have one major thing in common: They work best with WINDOWS closed! :D

mverrier
11-11-2007, 12:13 PM
Thanks for that intriguing looking script. I tried to flesh it out a bit to see how it works but I wasn't successful. Below it what I wrote. Do you think you could look at it and tell my what the issue with my implementation is? I'm sure that I don't fully understand your script but it is something I think I might be able to use. I apologize in advance for my crude javascript skills.

Thanks!!



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>

<script language="JavaScript">
<!--
function SwapMovie(url){
var so = new SWFObject(url, "mymovie", "400", "200", "8", "#336699");
so.write("flashcontent");
}

function removeChildren(elem) {
if (!elem) {
return false;
}
if (!elem.hasChildNodes()) {
return true;
}
while (elem.hasChildNodes()) {
elem.removeChild(elem.firstChild);
}
return true;
}
function appendChildren(parent, kids) {
for (var i=0; i<kids.length; i++) {
parent.appendChild(kids[i]);
}
}

function mkTxt (elem, string) {
var x = document.createElement(elem);
var y = document.createTextNode(string);
x.appendChild(y);
return x;
}

//-->
</script>

</head>



<body>


<table><tr><td onClick="appendChildren(div, [h2, p]);">Here is some text</td></tr></table>
<table><tr><td onClick="removeChildren(div); ">Here is some more text</td></tr></table>
<script language="JavaScript">
var div = document.getElementById("div");
var h2 = mkTxt("h2", "Page Title");
var p = mkTxt("p", "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla nec quam. Quisque est. Nunc tincidunt, sem quis accumsan tincidunt, leo ipsum ultrices quam, sed sodales eros elit non risus.");

</script>

</body>
</html>

TJ111
11-12-2007, 09:22 AM
You don't have any element with an id of "div". In your script, you could change "div" to "this" and it would probably work.

And to webjoel....What?
Edit: It's javascript, just put it in PHP tags for formatting purposes.

mverrier
11-13-2007, 05:49 PM
Thank you -- that does work. I appreciate your help. Thank you for posting these very nice functions!!

Monique.


Here it is for future reference for others who get stuck:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>

<script language="JavaScript">
<!--

function removeChildren(elem) {
if (!elem) {
return false;
}
if (!elem.hasChildNodes()) {
return true;
}
while (elem.hasChildNodes()) {
elem.removeChild(elem.firstChild);
}
return true;
}
function appendChildren(parent, kids) {
for (var i=0; i<kids.length; i++) {
parent.appendChild(kids[i]);
}
}

function mkTxt (elem, string) {
var x = document.createElement(elem);
var y = document.createTextNode(string);
x.appendChild(y);
return x;
}

//-->
</script>

</head>



<body>

<table>
<div id=div>
<tr><td onClick="appendChildren(this, [h2, p]);">Here is some text<hr></td></tr>

<tr><td onClick="removeChildren(this); ">Here is some more text</td></tr>
</div>

</table>
<script language="JavaScript">
var div = document.getElementById("div");
var h2 = mkTxt("h2", "Page Title");
var p = mkTxt("p", "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla nec quam. Quisque est. Nunc tincidunt, sem quis accumsan tincidunt, leo ipsum ultrices quam, sed sodales eros elit non risus.");
</script>

</body>
</html>

NogDog
11-15-2007, 07:35 AM
One of those things that gets done a lot. This one is short yet is smart enough to only truncate at some sort of space (space, newline, tab, etc.) instead of in the middle of a word:

<?php
/**
* Truncate string to no more than specified length, breaking only at a
* white space character. Adds ellipsis if string is truncated.
* @param string $text
* @param integer $length
* @return string
*/
function truncate($text, $length)
{
$length = abs((int)$length);
if(strlen($text) > $length)
{
$text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
}
return($text);
}
?>

toicontien
11-20-2007, 03:46 PM
Some that I continually find useful:
/**
* @class window
*
* @function getIndex
* Returns the index at which an item is found in an array
*
* @param needle (variable, required)
* The item to be found
*
* @param haystack (array, required)
* The array to be searched
*
* @return number
* Index number at which the item is found, or -1 if not found
*/
function getIndex(needle, haystack) {
for (var i=0, end=haystack.length; i<end; i++) {
if (haystack[i] == needle) {
return i;
}
}
return -1;
}


/**
* @class window
*
* @function inArray
* Tests to see if something is in an array.
*
* @param needle (variable, required)
* The item to find.
*
* @param haystack (array, required)
* The array to search.
*
* @return boolean
* True if it is found, false otherwise.
*/
function inArray(needle, haystack) {
for (var i=0, end=haystack.length; i < end; i++) {
if (haystack[i] == needle) {
return true;
}
}
return false;
}


/**
* @function popup
* Creates an accessible JavaScript pop up window link. Allows JavaScript-
* enabled browsers to open links in a new window and control its
* appearance, while allowing non JavaScript browsers to follow the link.
*
* @param el (object, required)
* Node reference to the clicked link.
*
* @return boolean
* If an invalid node reference is passed, true is returned to all the
* mouse click or pressed key event to continue. If all is well, a false
* value is returned to nullify the link click.
*/
function popup(el, opts) {
if (!el) {
return true;
}
var target = '_blank', url = el.href;
if (!opts) {
opts = '';
}
if (el.target !== '') {
target = el.target;
}
window.open(url, opts, target);
return false;
}


/**
* @class window
*
* @function submitForm
* Submits a form in one of two ways: by using the submit() function or
* clicking a button named "submit" since some older markup may contain
* FORMs that have buttons named "submit." When this happens, the form's
* submit function is overwritten with a reference to the button. This
* function will "click" the button when it is named "submit" and then
* it submits the form.
*
* @param frm (variable, required)
* The Id or node reference to a FORM tag.
*
* @return void
*/
function submitForm(frm) {
if (dom) {
if (typeof(frm) === 'string') {
frm = document.getElementById(frm);
}
if (typeof(frm.submit) === 'function') {
frm.submit();
} else if (frm.submit.click) {
frm.submit.click();
}
}
}

Kravvitz
11-20-2007, 04:53 PM
@toicontien

Don't you need to swap the 2nd and 3rd arguments to window.open()?

Have you seen the new features of JavaScript 1.6+ (http://developer.mozilla.org/en/docs/JavaScript)?

@NogDog Neat function. :cool:

toicontien
11-20-2007, 05:19 PM
@toicontien

Don't you need to swap the 2nd and 3rd arguments to window.open()?
I've got them swapped eh? Need to change that. :)

LeeU
11-21-2007, 09:52 AM
Ahhh, these look like fine pickings for the snippets section over at JavaScript Source (http://javascript.internet.com/). ;->

scragar
12-14-2007, 02:13 PM
I know it's kinda evil to use innerHTML, but it saves a lot of time writing this peice of ajax :P
var defaultpage = "ajax.php";
var multiquery = false;
var lookingfor = new Array();
var fillin = new Array();

lookingfor[lookingfor.length] = "cont";
fillin[fillin.length] = "cont";
// lookingfor[lookingfor.length] = "";
// fillin[fillin.length] = "";

var onfailure = true;
var errofunc = false;
var onbusy = false;
var busyfunc = false;
var defaultReturn = false;
var resultfunc = false;
var loadingelement = "";

// the real code here.

if(!multiquery){
var ajaxResponse = false;
};
function mkRequest(post, get, uri){
if(!uri)
var uri = defaultpage;
if(!get)
var get = "";
if(!SID)
var SID = "";
if(multiquery){
var ajaxResponse = false;
}else{
if(ajaxResponse){
if(busyfunc){
var tmp = busyfunc(ajaxResponse.status, ajaxResponse);
if(typeof(tmp) == "undefined")
return onbusy;
else
return tmp;
}else{
return onbusy;
};
};
};
if (window.XMLHttpRequest){ // the good browsers
ajaxResponse = new XMLHttpRequest();
}else
if(window.ActiveXObject){ // IE
try{
ajaxResponse = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try {// more IE :(
ajaxResponse = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
};
};
if (!ajaxResponse) {
return onfailure;
};
if(loadingelement)
document.getElementById(loadingelement).style.display = "block";
ajaxResponse.open('POST', uri+"?"+SID+get, false);
ajaxResponse.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxResponse.send(post);
if(loadingelement)
document.getElementById(loadingelement).style.display = "none";
if(ajaxResponse.status == 200){
var xmldoc = ajaxResponse.responseText;
if(!resultfunc || resultfunc(xmldoc, ajaxResponse)){
var reg;
var j;
for(var i = 0; i < lookingfor.length; i++){
reg = new RegExp("<\/?"+lookingfor[i]+">");
j = xmldoc.split(reg);
if(j.length == 3){
document.getElementById(fillin[i]).innerHTML = j[1];
};
};
};
ajaxResponse = false;
return defaultReturn;
}else{
if(errofunc){
var tmp = errofunc(ajaxResponse.status, ajaxResponse);
ajaxResponse = false;
if(typeof(tmp) == "undefined")
return onfailure;
else
return tmp;
}else{
ajaxResponse = false;
return onfailure;
};
};
};
and it's called like so:
caller.php
<html>
<head>
<script src="ajax.js"></script>
<script>
// this line set's the session ID for PHP scripts, handy if I do say so myself.
var SID = "<?=SID;?>";
</script>
</head>
<body>
<a href="#" onclick="return mkRequest('POST QUERY', 'GET QUERY', 'PAGE');">test</a>
<div id="cont">this content would change.</div>
</body></html>

of course this is just a very basic example(there is a lot you can do with it :P).


EDIT: thought I should explain it a little, the function uses ajax and innerHTML to update pages without reloading the full page, and without the negative effects of frames. if the function fails for 1 of 2 reasons then you can set behaviours and functions to tackle the instance, as can you write a function to handle the final result of the query. only the post query is essential, the url and get query's can both safely be ommited provided the javascript has a default page set.
I only wrote this myself because I belive the protype.js method of doing things like this is overly complicated for standard use, my function works fine on konqueror, opera, firefox and IE5-6(proberly 7 as well), so I don't see too much of a problem using it.