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

About this user

Alan Coleman www.alancoleman.co.uk

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

Finding the URL presented to the browser

Finding the URL presented to the browser, instead of the actual location of the page.

<SCRIPT LANGUAGE="JavaScript">
  
      <!--
      {
       document.write(location.href);
      }
      // -->
</SCRIPT>

Javascript document text replace

This will find any instance of a chosen word and swap it out for another (non case sensitive). It comes courtesy of a moderator on webdeveloper.com

<script type="text/javascript">
var words={
'Bill':'William','Miss':'Mrs'
}
var regs=[];
for(arg in words){regs[regs.length]=new RegExp(arg,'g')}

window.onload=function replaceText(){
var tags=document.getElementsByTagName('body')[0].getElementsByTagName('*');
var i=0,t;
	while(t=tags[i++]){
		if(t.childNodes[0]){
			var j=0, c;
			while(c=t.childNodes[j++]){
				if(c.nodeType==3){
					var k=0;
					for(arg in words){
						c.nodeValue=c.nodeValue.replace(regs[k],words[arg]);
						k++;
					}
				}
			}
		}
	}
}

target= not valid in XHTML

Used for pages with strict doctypes (i.e. no target="_blank"). Automagically adds them back in to links with rel="external"

function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
     anchor.target = "_blank";
    }

}
}
window.onload = externalLinks;

//////////////

<a href="whatever" rel="external" title="whatever">Whatever</a>

Form name not valid in strict XHTML

<form name="search" id="search"...

'name' is not valid in strict XHTML. So instead use the id

<form id="search"...

<a href="#" onclick="document.forms['search'].submit();return false" title="Search">Search</a>

DOM Image rollover

This is by Chris Poole (http://chrispoole.com) and it works really well.

function domRollover() {
if (navigator.userAgent.match(/Opera (\S+)/)) {
var operaVersion = parseInt(navigator.userAgent.match(/Opera (\S+)/)[1]);
}
if (!document.getElementById||operaVersion <7) return;
var imgarr=document.getElementsByTagName('img');
var imgPreload=new Array();
var imgSrc=new Array();
var imgClass=new Array();
for (i=0;i<imgarr.length;i++){
if (imgarr[i].className.indexOf('domroll')!=-1){
imgSrc[i]=imgarr[i].getAttribute('src');
imgClass[i]=imgarr[i].className;
imgPreload[i]=new Image();
if (imgClass[i].match(/domroll (\S+)/)) {
imgPreload[i].src = imgClass[i].match(/domroll (\S+)/)[1]
}
imgarr[i].setAttribute('xsrc', imgSrc[i]);
imgarr[i].onmouseover=function(){
this.setAttribute('src',this.className.match(/domroll (\S+)/)[1])
}
imgarr[i].onmouseout=function(){
this.setAttribute('src',this.getAttribute('xsrc'))
}
}
}
}
domRollover();

//

Where your image would look like this:

<img src="images/b_news.gif" alt="News" class="domroll images/b_news_roll.gif" />



Remove file extension from getAttribute('src')

This should set x to anything before an instance of the string ".gif"

  x=getAttribute('src')
  x=x.substring(0, x.indexOf('.gif'));

Formatting large numbers with a javascript function

This function will format a large number like 23000456 to 23,000,456

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

        example = addCommas(example);

Javascript commands from 'a' tags rather than buttons

In this instance the relevant form is called 'search_form'. This is specified in the a tag version because it's not an input and as such cannot have submit or reset associated with it.

    	<input type="submit" value="Search" onclick="javascript:return text_validate()" />
   	<input type="reset" value="Reset" />
    	<input type="button" value="Show All News" onclick="javascript:return showAll();" title="Show all news button." />

Could be shown as:

        <a class="blockbutton" title="Search" href="javascript:document.search_form.submit();" onclick="javascript:return text_validate();">Search</a>	
	<a class="blockbutton" title="Reset" href="javascript:document.search_form.reset();">Reset</a>
	<a class="blockbutton" title="Show All News" href="javascript:showAll();">Show All News</a>



Okay, as pointed out by Blonkm this is bad for usability. A better way of doing things would be like this:

<script type="text/javascript">
  function doSubmit(){    
        document.getElementById("whatever").submit();
        return true;   
     }   
</script>

<a href="#" onclick="doSubmit();return false;" title="Search">Link</a>

An alternative to the Input Type = "Submit" button

The standard HTML element for users to submit a form is the <input type="submit"> button. Though it is possible to change the formatting of the standard grey button to a certain degree, you can't utilise rollover states.

If you want greater control over the design of the submit button, then an alternative is to use an anchor link, with a Javascript function to submit the form. The format is as follows:


<a href="javascript:void(document.[form name attribute].submit())">[Link text]</a>

eg: <a href="javascript:void(document.frmForm.submit())">Submit this Book Review to us!</a>



You can then utilise style classes the same as you would for any other anchor link.

If you need to do some JavaScript form validation, then simply replace the submit call with the name of your JavaScript function to validate the form, and move the submit call to the end of the form validation function code.

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS