HTML and CSS Reference
In-Depth Information
The OnChange event-handler function grabs the selected files using the iles property of the file field
control. OnChange then calls a helper function ShowFileDetails() that displays a list of files selected as
anchor elements.
OnDrop grabs the files using the iles property of the dataTransfer object and cancels event bubbling.
ShowFileDetails() is then called.
The ShowFileDetails() function is shown in Listing 9-28.
Listing 9-28. ShowFileDetails() Function
function ShowFileDetails() {
var html = "";
html += files.length + " files selected!";
html += "<div class='ileName'>"
for(var i=0;i<iles.length;i++)
{
if (files[i].type == "text/xml") {
html += "<a href='#' data-ile-index='" + i + "'>" + files[i].name + "</a> ";
}
else {
html += "<span data-ile-index='" + i + "'>" + files[i].name + "</span> ";
}
}
html += "</div>";
$("#ilecount").html(html);
$("a").hover(ShowPreview,HidePreview);
}
The application is intended to upload XML files only, and hence only XML files can be previewed.
ShowFileDetails() iterates through the selected files ( iles global variable) and checks the type property of
every File object. For XML files, the type property returns text/xml ; only such file names are displayed as
anchors. Other file types are displayed as <span> elements and hence can't be previewed.
The jQuery hover() method binds to the hyperlink elements two handler functions that are invoked
when the mouse pointer enters and leaves the hyperlinks. The ShowPreview() function is responsible for
displaying a short preview of the XML file in the tooltip. This is done by setting the title attribute of the
corresponding anchor elements. Listing 9-29 shows ShowPreview() .
Listing 9-29. ShowPreview() Function
function ShowPreview(evt) {
evt.stopPropagation();
evt.preventDefault();
var reader = new FileReader();
$(reader).bind("load", function (e) {
var xmlData = e.target.result;
if (xmlData.length > 500) {
xmlData = xmlData.substr(0, 500);
}
$(evt.target).attr('title', xmlData);
});
var fileIndex = $(evt.target).attr('data-file-index');
reader.readAsText(files[fileIndex]);
}
 
Search WWH ::




Custom Search