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

« Newer Snippets
Older Snippets »
Showing 1-10 of 22 total  RSS 

Firefox 3 and input file

The nsIDOMFile interface retrieves data from a file submitted to a form using the input type "file". This allows the file reference to be saved when the form is submitted while the user is using a web application offline, so that the data can be retrieved and uploaded once the Internet connection is restored.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>input type=file & Firefox 3</title>
</head>

<body>
	
<h1>input type=file & Firefox 3</h1>
	
<script type="text/javascript">
// <![CDATA[

function inputFileOnChange() {
	var v_console = '';
	v_console += 'value: ' + document.getElementById('my-file').value;
	v_console += '<br \/>';
	
	if(document.getElementById('my-file').files) {
		// Support: nsIDOMFile, nsIDOMFileList
		v_console += 'files.length: ' + document.getElementById('my-file').files.length;
		v_console += '<br \/>';
		
		v_console += 'fileName: ' + document.getElementById('my-file').files.item(0).fileName;
		v_console += '<br \/>';
		
		v_console += 'fileSize: ' + document.getElementById('my-file').files.item(0).fileSize;
		v_console += '<br \/>';
		
		v_console += 'data: ' + document.getElementById('my-file').files.item(0).getAsDataURL();
//		v_console += 'data: ' + document.getElementById('my-file').files.item(0).getAsBinary();
//		v_console += 'data: ' + document.getElementById('my-file').files.item(0).getAsText();
		v_console += '<br \/>';
	};
	
	document.getElementById('console').innerHTML = v_console;
};

// ]]>
</script>
	
<div>
	<input type="file" name="my-file" id="my-file" onchange="inputFileOnChange();" />
	<br /><br />
	<code id="console">...console...< /code>
</div>
	
</body>
</html>


Source: Firefox 3 and input type=file , upload file

Draft -- QuickAdd complementary functions QuickRemove, QuickToggle, wasQuickAdded

// FoxyProxy - modules/superadd.js
//
// Replace the original onQuickAdd() function with the following code.
// Then re-launch Firefox.app

  onQuickAdd : function(window, doc) {
    var url = doc.location.href;
    var match = this.getPatternFromTemplate(window, url);
    if (match) {
      // Check for duplicates and exclusions due to black lists
      var m = match.isBlackList ? this.proxy.isBlackMatch(match.pattern, url) : this.proxy.isWhiteMatch(match.pattern, url);
      if (m) {
	    this._notify && this.fp.notifier.alert(this.fp.getMessage(this.notificationTitle),
	      fp.getMessage("superadd.url.added", [m.pattern, this._proxy.name]));
      }
      else
        this.addPattern(match, doc.location);
    }
  },  

  onQuickRemove : function(window, doc) {
    var url = doc.location.href;
    var match = this.getPatternFromTemplate(window, url);
    if (match) {
      // Check for duplicates and exclusions due to black lists
      var m = match.isBlackList ? this.proxy.isBlackMatch(match.pattern, url) : this.proxy.isWhiteMatch(match.pattern, url);
      if (m) {
		this.proxy.matches = this.proxy.matches.filter(function(e) {return e != m;});
		this.fp.writeSettings();

        this._notifyWhenCanceled &&
          this.fp.notifier.alert(this.fp.getMessage("foxyproxy.quickadd.label"),
            this.fp.getMessage("quickadd.quickadd.canceled", [m.name, this._proxy.name]));

		this._reload && loc.reload();
      }
      else
        ;// No match; nothing removed
    }
  },  


  onQuickToggle : function(window, doc) {
    var url = doc.location.href;
    var match = this.getPatternFromTemplate(window, url);
    if (match) {
      // Check for duplicates and exclusions due to black lists
      var m = match.isBlackList ? this.proxy.isBlackMatch(match.pattern, url) : this.proxy.isWhiteMatch(match.pattern, url);
      if (m) {
		this.proxy.matches = this.proxy.matches.filter(function(e) {return e != m;});
		this.fp.writeSettings();

        this._notifyWhenCanceled &&
          this.fp.notifier.alert(this.fp.getMessage("foxyproxy.quickadd.label"),
            this.fp.getMessage("quickadd.quickadd.canceled", [m.name, this._proxy.name]));

		this._reload && loc.reload();
      }
      else
        this.addPattern(match, doc.location);
    }
  },  


  wasQuickAdded : function(window, doc) {
    var url = doc.location.href;
    var match = this.getPatternFromTemplate(window, url);
    if (match) {
      // Check for duplicates and exclusions due to black lists
      var m = match.isBlackList ? this.proxy.isBlackMatch(match.pattern, url) : this.proxy.isWhiteMatch(match.pattern, url);
      if (m) {
        return true;
      }
      else
        return false;
    }
	return false;
  },  

Simple javascript XHR object with fix for missing onreadystatechange event in Firefox (for synchronous calls)

This code fixes the issue in Firefox where the onreadystatechange event is not called for synchronous XHR requests. It is based on the XHConn script from http://xkr.us/code/javascript/XHConn/, patched with the fix documented at http://lukav.com/wordpress/2007/04/12/firefox-firebug-and-synchronos-calls-problem/

/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
/**
 * Modified slightly from original to support synchoronous transactions
 * CDB 2007-05-16, 2007-06-05
 */

function XHConn()
{
	var xmlhttp, bComplete = false;
	try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
	catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
	catch (e) { try { xmlhttp = new XMLHttpRequest(); }
	catch (e) { xmlhttp = false; }}}
	if (!xmlhttp) return null;
	this.connect = function(sURL, sMethod, sVars, fnDone, bAsynch)
	{
		if (!xmlhttp) return false;
		bComplete = false;
		sMethod = sMethod.toUpperCase();

		if (bAsynch == null) bAsynch = true; //treat asynch as an optional argument

		try {
			if (sMethod == "GET")
			{
				xmlhttp.open(sMethod, sURL+"?"+sVars, (bAsynch == true));
				sVars = "";
			}
			else
			{
				xmlhttp.open(sMethod, sURL, (bAsynch == true));
				xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
				xmlhttp.setRequestHeader("Content-Type",
					"application/x-www-form-urlencoded");
			}

			xmlhttp.onreadystatechange = function(){
				if (xmlhttp.readyState == 4 && !bComplete)
				{
					bComplete = true;
					fnDone(xmlhttp);
				}
			};
			xmlhttp.send(sVars);

			/**
			 * Firefox <= 2.0.0 doesn't fire onreadystatechange for synchronous requests.
			 * See http://lukav.com/wordpress/2007/04/12/firefox-firebug-and-synchronos-calls-problem/
			 */
			var isGecko = (document.addEventListener) ? true : false;
			try {
				if (!bAsynch && isGecko && xmlhttp.onreadystatechange == null) {
					bComplete = true;
					fnDone(xmlhttp);
					return true;
				}
			}
			catch (e) { return false; }
			/**
			 * End synchronous request patch
			 */
		}
		catch(z) { return false; }
		return true;
	};
	return this;
}

firefox not showing vertical scrollbars in blog

hey everyone,

I'm new here and wondering if someone can help me out. i have a couple wordpress blogs i've built for clients, and i'm occasionally getting a wierd behavior in Firefox Win/Mac: sometimes even though there is plenty of content below the fold, no vertical scrollbar will show at all. it only does this on firefox.

here's an example (must view in firefox):

http://www.lorihedrickphotography.com/blog/

and i've tried adding this:


html {
height:101%;
overflow-y:scroll;
}


i looked at it with firebug, it validates. i'm stumped! any help would be greatly appreciated.

-jared

Using XPath in JavaScript (Mozilla based)

The following JavaScript code uses XPath to select a specific element. Note: This code works for Firefox, but Internet Explorer has it's own implementation of XPath. see Introduction to using XPath in JavaScript [mozilla.org]

doc (xml document)
<codes>
  <codex value='bQ' index='Q'/>
  <codex value='S' index='R'/>
  <codex value='PU' index='S'/>
  <codex value='ji' index='T'/>
  <codex value='0' index='U'/>
  <codex value='33' index='V'/>
  <codex value='A' index='W'/>
  <codex value='tO' index='X'/>
  <codex value='fW' index='Y'/>
  <codex value='P' index='Z'/>
  <codex value='4h' index='a'/>
  <codex value='B' index='b'/>
  <codex value='m' index='c'/>
  <codex value='qf' index='d'/>
  <codex value='uJ' index='e'/>
</codes>


Assuming the doc object below contains the XML data from above.
var nodesSnapshot = doc.evaluate("codes/codex[@index='a']", doc, null, XPathResult.
  UNORDERED_NODE_SNAPSHOT_TYPE, null );
node = nodesSnapshot.snapshotItem(0);
msg = "The secret code for '" + node.getAttribute('index') + "' is " + node.getAttribute('value');
alert(msg);


output (value from the alert box)
"The secret code for 'a' is 4h"


see also: Reading an XML file using JavaScript

Crack open Firefox's new Places sqlite database with ActiveRecord

require "rubygems"
require "active_record"
require "active_support"

ActiveRecord::Base.establish_connection(
	:adapter => "sqlite3",
	:database => "places.sqlite"
)

class MozHistoryvisit < ActiveRecord::Base
	belongs_to :place, :class_name => "MozPlaces", :foreign_key => "place_id"
end

class MozPlaces < ActiveRecord::Base
end

p Time.now.yesterday
from = Time.now.yesterday.to_i * 1000000

MozHistoryvisit.find(:all, :conditions => ["visit_date > ?", from]).each do |h|
	place = h.place
	puts place.title
	puts place.url
	puts place.visit_count
	puts
end

JavaScript Fill Textarea from HTML Select not working with FireFox or Opera but does in IE6

//
// Fill textarea with keywords from HTML Select element
//

This code DOES work in I.E6 (on my machine (XP pro), but doesn't work in Firefox 2.0.0.4 or Opera 9.0.2

The idea is to be able to either type in the text area directly or choose from a list of saved words in the select box. When a new choice is made from the select, it automatically gets inserted into the text area.

With Firefox , when the page is first loaded, I can choose from the select control and it works until I type something in the text area, and then it stops working.

With Opera 9.02, the select control doesn't work at all.

IE6, works fine.

Any hints tips, appreciated, as I'm a novice with javascript / DOM programming.

I quite possibly am not using the most correct / efficient document.XXX calls here.


Mike

You can test it at http://mstramba.com/fb5.html

///////////////
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <style type="text/css">textarea {  height:200px; width:50%;}</style>

<script type="text/javascript">

function htmlData(selectValue,targetTextArea)
{
//   alert("select box changed to : '" + selectValue + "'");

   var txtNode=document.createTextNode(selectValue);
   var textArea=document.getElementById(targetTextArea);
   textArea.appendChild(txtNode);
}
</script>
</head>

<body>
 <form method="post">
 <select name="country" id="selbox" onchange="htmlData(this.value,'content')" />
   <option value="#">-Select-</option>
   <option value="SuperCaliFragilisticExpiAliDocius">SuperCaliFragilisticExpiAliDocius</option>
   <option value="Discombombulatively">Discombombulatively</option>
   <option value="I don't understand how this can be happening">I don't understand how this can be happening</option>
 </select>

 <textarea name="content" id="content">Type some text or choose words from the select control</textarea>

 <input type="submit" />
</form>
</body>
</html>

Babelfish translate

Ok, so maybe some of you might think that Babelfish's the best translator out there. I don't know about that , but I do know where my towel is ;)
So, boys and girls, here's the bookmarklet that allows to translate your current web-page using the babelfish translation engine.

javascript:location.href='http://babelfish.altavista.com/babelfish/tr?trurl='+encodeURIComponent(location.href)+'&lp=%s&btnTrUrl=Translate'


To make it useful, save it as a bookmark in FF (or as a new search engine in Opera) and give it a keyword/shortcut by editing the bookmark's properties in FF (or the search properties in Opera). Let's call him, say 'bf', that should do it.

Here are some examples:
bf en_fr
bf fr_en
bf en_ja


Enjoy!
G.R.

Chickenfoot shortcut script

Here's a little script to get Chickenfoot to add some keyboard shortcuts to firefox.

Add this to run as a trigger on window open and you'll be able to acquire focus on the current chickenfoot editor window by pressing 'alt-C' and to regain focus on the main tab (which is something I've often wanted to be able to do) with 'alt-D'

// attach keyboard shortcut (Alt-C)
chromeWindow.addEventListener("keypress",
   function(event) {
     if (event.altKey && event.charCode == 'c'.charCodeAt(0)) {
       event.preventDefault();
       var sidebar = Chickenfoot.getSidebarWindow(chromeWindow);
       if (sidebar) {
          sidebar.getSelectedBuffer().focus();
       }
     }
    },
    true);


// attach keyboard shortcut (Alt-D)
chromeWindow.addEventListener("keypress",
   function(event) {
     if (event.altKey && event.charCode == 'd'.charCodeAt(0)) {
       event.preventDefault();
	   tab.focus();
       }
    },
    false);



How to create a OpenSearch reference for your site (as used by Firefox 2's search box)

Create a file like this one as used for Wikipedia, but that refers to your own site's search:

<?xml version="1.0"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
<ShortName>Wikipedia (English)</ShortName>
<Description>Wikipedia (English)</Description>
<Image height="16" width="16" type="image/x-icon">http://en.wikipedia.org/favicon.ico</Image>
<Url type="text/html" method="get" template="http://en.wikipedia.org/w/index.php?title=Special:Search&amp;search={searchTerms}"/>
<Url type="application/x-suggestions+json" method="GET" template="http://en.wikipedia.org/w/api.php?action=opensearch&amp;search={searchTerms}"/>
</OpenSearchDescription>


Then link to it from your pages like so:

<link rel="search" type="application/opensearchdescription+xml" href="/w/opensearch_desc.php" title="Wikipedia (English)" />
« Newer Snippets
Older Snippets »
Showing 1-10 of 22 total  RSS