How do I load a my Java applet on a Click event? - java

I have a div where I load a Java applet, but the new version of Java is giving an unsigned certificate error:
I would like to know if I can restrict the loading of my Java applet (DeployJava.RunApplet), currently instantiated while the page is loaded, to only load when user clicks the View in 3D button?
Applet loading code:
<div id="appletContainer" runat="server" style="width:(document.body.clientWidth - 270);height:300" clientidmode="Static">
<script type="text/javascript">
var showCI = 0;
if (document.getElementById("hdnHas3D").value == "1" && !isAppleMobile()) {
var J3DStyleID = document.getElementById("hdn3DStyleID").value;
var code = "com.wirefusion.player.AppletPlayer";
var archiveList = "Some achive List";
var width = document.body.clientWidth - 270;
var height = 300;
var attributes = {
id: "appletContainerX",
name: J3DStyleID,
code: code,
codebase: ".",
width: width,
height: height,
mayscript: "true"
};
var parameters = {
progressFunc: "handleAppletProgress",
archive: archiveList,
java_arguments: "-Xmx200m",
regid: "6050-25",
resourcefolder: "/RichContent/3D_Vehicles/J3D/Vehicles/" + J3DStyleID + "/",
preloadfile: J3DStyleID + ".jar",
environmentType: "WEBSITE",
environmentWidth: width,
environmentHeight: height,
groupsXMLFile: "../../Resources/groups.xml",
vehicleXMLFile: J3DStyleID + ".xml"
};
var version = '1.6.0_20';
if (deployJava.versionCheck(version + '+')) {
docWriteWrapper(function () {
deployJava.runApplet(attributes, parameters, version);
});
} else {
if (document.getElementById("iframeContainer").style.display != "none") {
alert("Unable to load Interactive mode");
showCI = 1;
}
}
}
</script>
</div>

Don't include the regular <applet> (or <object>) tag in your HTML. Instead follow this tutorial on how to do dynamically add it to your page, using JavaScript.
HTML 4
function loadApplet(code,codebase,width,height,alt){
var placeholder=document.getElementById('placeholder');
if(window.opera){
placeholder.innerHTML='<applet code="'+code+'" codebase="'+codebase+'" width="'+width+'" height="'+height+'" alt="'+alt+'"></applet>';
}else{
var a=document.createElement('applet');
a.setAttribute('code',code);
a.setAttribute('codebase',codebase);
a.setAttribute('width',width);
a.setAttribute('height',height);
a.setAttribute('alt',alt);
placeholder.appendChild(a);
}
}
HTML 5
function loadApplet(code,codebase,width,height,alt){
var placeholder=document.getElementById('placeholder');
var a = document.createElement('object');
a.setAttribute('type','application/x-java-applet');
a.setAttribute('width',width);
a.setAttribute('height',height);
a.setAttribute('alt',alt);
var codeParam = document.createElement('param');
codeParam.setAttribute('name','code');
codeParam.setAttribute('value',code);
a.appendChild(codeParam);
var codebaseParam = document.createElement('param');
codebaseParam.setAttribute('name','codebase');
codebaseParam.setAttribute('value',codebase);
a.appendChild(codebaseParam);
placeholder.appendChild(a);
}
In your HTML create a placeholder DIV, i.e. where you want to it to be loaded into, and a link to load your applet. You will need to customise the values in the load link to your values of the Applet.
<div id="placeholder"></div>
<input type="button" value="Load Applet" onclick="loadApplet('TestApplet.class','.','200','300','demo applet')" />
The linked tutorial explains more about how to make it pretty. The code above is just simply the concept.
Update since modification of question
Your code appears to load the applet using JavaScript already. The problem is the script is being run as soon as the page is loaded and not when the user clicks on the View in 3D button.
To prevent it running immediately, you can wrap the loader code in a function called loadApplet. So explained in pseudo code:
function loadApplet() {
// Your existing applet loading code
}
So using your included source code, I have wrapped it with a function, which will prevent it running when your page is loaded.
<div id="appletContainer" runat="server" style="width:(document.body.clientWidth - 270);height:300" clientidmode="Static">
<script type="text/javascript">
// Wrap your code with a function called loadApplet
function loadApplet() {
// Your applet loading code:
var showCI = 0;
if (document.getElementById("hdnHas3D").value == "1" && !isAppleMobile()) {
var J3DStyleID = document.getElementById("hdn3DStyleID").value;
var code = "com.wirefusion.player.AppletPlayer";
var archiveList = "Some achive List";
var width = document.body.clientWidth - 270;
var height = 300;
var attributes = {
id: "appletContainerX",
name: J3DStyleID,
code: code,
codebase: ".",
width: width,
height: height,
mayscript: "true"
};
var parameters = {
progressFunc: "handleAppletProgress",
archive: archiveList,
java_arguments: "-Xmx200m",
regid: "6050-25",
resourcefolder: "/RichContent/3D_Vehicles/J3D/Vehicles/" + J3DStyleID + "/",
preloadfile: J3DStyleID + ".jar",
environmentType: "WEBSITE",
environmentWidth: width,
environmentHeight: height,
groupsXMLFile: "../../Resources/groups.xml",
vehicleXMLFile: J3DStyleID + ".xml"
};
var version = '1.6.0_20';
if (deployJava.versionCheck(version + '+')) {
docWriteWrapper(function () {
deployJava.runApplet(attributes, parameters, version);
});
} else {
if (document.getElementById("iframeContainer").style.display != "none") {
alert("Unable to load Interactive mode");
showCI = 1;
}
}
}
}
</script>
</div>
Then to your View in 3D element you must add an onclick attribute calling the loadApplet() function. For example:
<input type="button" value="Show in 3D" onclick="loadApplet()" />
Note: It may be the case that your View in 3D button already has an onclick attribute wired to a function that brings your applet into view, in which case you would still want this to be called after your load function. I have used showApplet() as an example, this is most likely different for you.
<input type="button" value="Show in 3D" onclick="loadApplet(); showApplet();" />
If you provide the code for your Show in 3D button, I can better assist you here.

Related

export multiple pdf files for multiple list using JasperPrint in java [duplicate]

I am not sure if this is possible using standard web technologies.
I want the user to be able to download multiple files in a single action. That is click check boxes next to the files, and then get all the files that were checked.
Is it possible - if so what basic strategy do you recommend. I know I can use comets technology to create server side events that trigger an HttpResponse but I am hoping there is a simpler way.
var links = [
'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.exe',
'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.dmg',
'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.jar'
];
function downloadAll(urls) {
var link = document.createElement('a');
link.setAttribute('download', null);
link.style.display = 'none';
document.body.appendChild(link);
for (var i = 0; i < urls.length; i++) {
link.setAttribute('href', urls[i]);
link.click();
}
document.body.removeChild(link);
}
<button onclick="downloadAll(window.links)">Test me!</button>
HTTP does not support more than one file download at once.
There are two solutions:
Open x amount of windows to initiate the file downloads (this would be done with JavaScript)
preferred solution create a script to zip the files
You can create a temporary set of hidden iframes, initiate download by GET or POST inside of them, wait for downloads to start and remove iframes:
<!DOCTYPE HTML>
<html>
<body>
<button id="download">Download</button>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$('#download').click(function() {
download('http://nogin.info/cv.doc','http://nogin.info/cv.doc');
});
var download = function() {
for(var i=0; i<arguments.length; i++) {
var iframe = $('<iframe style="visibility: collapse;"></iframe>');
$('body').append(iframe);
var content = iframe[0].contentDocument;
var form = '<form action="' + arguments[i] + '" method="GET"></form>';
content.write(form);
$('form', content).submit();
setTimeout((function(iframe) {
return function() {
iframe.remove();
}
})(iframe), 2000);
}
}
</script>
</body>
</html>
Or, without jQuery:
function download(...urls) {
urls.forEach(url => {
let iframe = document.createElement('iframe');
iframe.style.visibility = 'collapse';
document.body.append(iframe);
iframe.contentDocument.write(
`<form action="${url.replace(/\"/g, '"')}" method="GET"></form>`
);
iframe.contentDocument.forms[0].submit();
setTimeout(() => iframe.remove(), 2000);
});
}
This solution works across browsers, and does not trigger warnings. Rather than creating an iframe, here we creates a link for each file. This prevents warning messages from popping up.
To handle the looping part, we use setTimeout, which is necessary for it to work in IE.
Update 2021: I am aware that the "run code snippet" no longer works, but that's due to cross site cookie issues. The code works fine if deployed on your own site.
/**
* Download a list of files.
* #author speedplane
*/
function download_files(files) {
function download_next(i) {
if (i >= files.length) {
return;
}
var a = document.createElement('a');
a.href = files[i].download;
a.target = '_parent';
// Use a.download if available, it prevents plugins from opening.
if ('download' in a) {
a.download = files[i].filename;
}
// Add a to the doc for click to work.
(document.body || document.documentElement).appendChild(a);
if (a.click) {
a.click(); // The click method is supported by most browsers.
} else {
$(a).click(); // Backup using jquery
}
// Delete the temporary link.
a.parentNode.removeChild(a);
// Download the next file with a small timeout. The timeout is necessary
// for IE, which will otherwise only download the first file.
setTimeout(function() {
download_next(i + 1);
}, 500);
}
// Initiate the first download.
download_next(0);
}
<script>
// Here's a live example that downloads three test text files:
function do_dl() {
download_files([
{ download: "https://stackoverflow.com/robots.txt", filename: "robots.txt" },
{ download: "https://www.w3.org/TR/PNG/iso_8859-1.txt", filename: "standards.txt" },
{ download: "http://qiime.org/_static/Examples/File_Formats/Example_Mapping_File.txt", filename: "example.txt" },
]);
};
</script>
<button onclick="do_dl();">Test downloading 3 text files.</button>
The following script done this job gracefully.
var urls = [
'https://images.pexels.com/photos/432360/pexels-photo-432360.jpeg',
'https://images.pexels.com/photos/39899/rose-red-tea-rose-regatta-39899.jpeg'
];
function downloadAll(urls) {
for (var i = 0; i < urls.length; i++) {
forceDownload(urls[i], urls[i].substring(urls[i].lastIndexOf('/')+1,urls[i].length))
}
}
function forceDownload(url, fileName){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
}
xhr.send();
}
Easiest way would be to serve the multiple files bundled up into a ZIP file.
I suppose you could initiate multiple file downloads using a bunch of iframes or popups, but from a usability standpoint, a ZIP file is still better. Who wants to click through ten "Save As" dialogs that the browser will bring up?
A jQuery version of the iframe answers:
function download(files) {
$.each(files, function(key, value) {
$('<iframe></iframe>')
.hide()
.attr('src', value)
.appendTo($('body'))
.load(function() {
var that = this;
setTimeout(function() {
$(that).remove();
}, 100);
});
});
}
I agree that a zip file is a neater solution... But if you have to push multiple file, here's the solution I came up with. It works in IE 9 and up (possibly lower version too - I haven't tested it), Firefox, Safari and Chrome. Chrome will display a message to user to obtain his agreement to download multiple files the first time your site use it.
function deleteIframe (iframe) {
iframe.remove();
}
function createIFrame (fileURL) {
var iframe = $('<iframe style="display:none"></iframe>');
iframe[0].src= fileURL;
$('body').append(iframe);
timeout(deleteIframe, 60000, iframe);
}
// This function allows to pass parameters to the function in a timeout that are
// frozen and that works in IE9
function timeout(func, time) {
var args = [];
if (arguments.length >2) {
args = Array.prototype.slice.call(arguments, 2);
}
return setTimeout(function(){ return func.apply(null, args); }, time);
}
// IE will process only the first one if we put no delay
var wait = (isIE ? 1000 : 0);
for (var i = 0; i < files.length; i++) {
timeout(createIFrame, wait*i, files[i]);
}
The only side effect of this technique, is that user will see a delay between submit and the download dialog showing. To minimize this effect, I suggest you use the technique describe here and on this question Detect when browser receives file download that consist of setting a cookie with your file to know it has started download. You will have to check for this cookie on client side and to send it on server side. Don't forget to set the proper path for your cookie or you might not see it. You will also have to adapt the solution for multiple file download.
Angular solution:
HTML
<!doctype html>
<html ng-app='app'>
<head>
<title>
</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body ng-cloack>
<div class="container" ng-controller='FirstCtrl'>
<table class="table table-bordered table-downloads">
<thead>
<tr>
<th>Select</th>
<th>File name</th>
<th>Downloads</th>
</tr>
</thead>
<tbody>
<tr ng-repeat = 'tableData in tableDatas'>
<td>
<div class="checkbox">
<input type="checkbox" name="{{tableData.name}}" id="{{tableData.name}}" value="{{tableData.name}}" ng-model= 'tableData.checked' ng-change="selected()">
</div>
</td>
<td>{{tableData.fileName}}</td>
<td>
<a target="_self" id="download-{{tableData.name}}" ng-href="{{tableData.filePath}}" class="btn btn-success pull-right downloadable" download>download</a>
</td>
</tr>
</tbody>
</table>
<a class="btn btn-success pull-right" ng-click='downloadAll()'>download selected</a>
<p>{{selectedone}}</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
</body>
</html>
app.js
var app = angular.module('app', []);
app.controller('FirstCtrl', ['$scope','$http', '$filter', function($scope, $http, $filter){
$scope.tableDatas = [
{name: 'value1', fileName:'file1', filePath: 'data/file1.txt', selected: true},
{name: 'value2', fileName:'file2', filePath: 'data/file2.txt', selected: true},
{name: 'value3', fileName:'file3', filePath: 'data/file3.txt', selected: false},
{name: 'value4', fileName:'file4', filePath: 'data/file4.txt', selected: true},
{name: 'value5', fileName:'file5', filePath: 'data/file5.txt', selected: true},
{name: 'value6', fileName:'file6', filePath: 'data/file6.txt', selected: false},
];
$scope.application = [];
$scope.selected = function() {
$scope.application = $filter('filter')($scope.tableDatas, {
checked: true
});
}
$scope.downloadAll = function(){
$scope.selectedone = [];
angular.forEach($scope.application,function(val){
$scope.selectedone.push(val.name);
$scope.id = val.name;
angular.element('#'+val.name).closest('tr').find('.downloadable')[0].click();
});
}
}]);
working example: https://plnkr.co/edit/XynXRS7c742JPfCA3IpE?p=preview
To solve this, I created a JS library to stream multiple files directly into a zip on the client-side. The main unique feature is that it has no size limits from memory (everything is streamed) nor zip format (it uses zip64 if the contents are more than 4GB).
Since it doesn't do compression, it is also very performant.
Find "downzip" it on npm or github!
This works in all browsers (IE11, firefox, Edge, Chrome and Chrome Mobile) My documents are in multiple select elements. The browsers seem to have issues when you try to do it too fast... So I used a timeout.
//user clicks a download button to download all selected documents
$('#downloadDocumentsButton').click(function () {
var interval = 1000;
//select elements have class name of "document"
$('.document').each(function (index, element) {
var doc = $(element).val();
if (doc) {
setTimeout(function () {
window.location = doc;
}, interval * (index + 1));
}
});
});
This is a solution that uses promises:
function downloadDocs(docs) {
docs[0].then(function (result) {
if (result.web) {
window.open(result.doc);
}
else {
window.location = result.doc;
}
if (docs.length > 1) {
setTimeout(function () { return downloadDocs(docs.slice(1)); }, 2000);
}
});
}
$('#downloadDocumentsButton').click(function () {
var files = [];
$('.document').each(function (index, element) {
var doc = $(element).val();
var ext = doc.split('.')[doc.split('.').length - 1];
if (doc && $.inArray(ext, docTypes) > -1) {
files.unshift(Promise.resolve({ doc: doc, web: false }));
}
else if (doc && ($.inArray(ext, webTypes) > -1 || ext.includes('?'))) {
files.push(Promise.resolve({ doc: doc, web: true }));
}
});
downloadDocs(files);
});
By far the easiest solution (at least in ubuntu/linux):
make a text file with the urls of the files to download (i.e. file.txt)
put the 'file.txt' in the directory where you want to download the files
open the terminal in the download directory from the previous lin
download the files with the command 'wget -i file.txt'
Works like a charm.
To improve on #Dmitry Nogin's answer: this worked in my case.
However, it's not tested, since I am not sure how the file dialogue works on various OS/browser combinations. (Thus community wiki.)
<script>
$('#download').click(function () {
download(['http://www.arcelormittal.com/ostrava/doc/cv.doc',
'http://www.arcelormittal.com/ostrava/doc/cv.doc']);
});
var download = function (ar) {
var prevfun=function(){};
ar.forEach(function(address) {
var pp=prevfun;
var fun=function() {
var iframe = $('<iframe style="visibility: collapse;"></iframe>');
$('body').append(iframe);
var content = iframe[0].contentDocument;
var form = '<form action="' + address + '" method="POST"></form>';
content.write(form);
$(form).submit();
setTimeout(function() {
$(document).one('mousemove', function() { //<--slightly hacky!
iframe.remove();
pp();
});
},2000);
}
prevfun=fun;
});
prevfun();
}
</script>
I am looking for a solution to do this, but unzipping the files in javascript was not as clean as I liked. I decided to encapsulate the files into a single SVG file.
If you have the files stored on the server (I don't), you can simply set the href in the SVG.
In my case, I'll convert the files to base64 and embed them in the SVG.
Edit: The SVG worked very well. If you are only going to download the files, ZIP might be better. If you are going to display the files, then SVG seems superior.
When using Ajax components it is possible to start multiple downloads. Therefore you have to use https://cwiki.apache.org/confluence/display/WICKET/AJAX+update+and+file+download+in+one+blow
Add an instance of AJAXDownload to your Page or whatever. Create an AjaxButton and override onSubmit. Create an AbstractAjaxTimerBehavior and start downloading.
button = new AjaxButton("button2") {
private static final long serialVersionUID = 1L;
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form)
{
MultiSitePage.this.info(this);
target.add(form);
form.add(new AbstractAjaxTimerBehavior(Duration.milliseconds(1)) {
#Override
protected void onTimer(AjaxRequestTarget target) {
download.initiate(target);
}
});
}
Happy downloading!
Below code 100% working.
Step 1: Paste below code in index.html file
<!DOCTYPE html>
<html ng-app="ang">
<head>
<title>Angular Test</title>
<meta charset="utf-8" />
</head>
<body>
<div ng-controller="myController">
<button ng-click="files()">Download All</button>
</div>
<script src="angular.min.js"></script>
<script src="index.js"></script>
</body>
</html>
Step 2: Paste below code in index.js file
"use strict";
var x = angular.module('ang', []);
x.controller('myController', function ($scope, $http) {
var arr = [
{file:"http://localhost/angularProject/w3logo.jpg", fileName: "imageone"},
{file:"http://localhost/angularProject/cv.doc", fileName: "imagetwo"},
{file:"http://localhost/angularProject/91.png", fileName: "imagethree"}
];
$scope.files = function() {
angular.forEach(arr, function(val, key) {
$http.get(val.file)
.then(function onSuccess(response) {
console.log('res', response);
var link = document.createElement('a');
link.setAttribute('download', val.fileName);
link.setAttribute('href', val.file);
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
.catch(function onError(error) {
console.log('error', error);
})
})
};
});
NOTE : Make sure that all three files which are going to download will be placed in same folder along with angularProject/index.html or angularProject/index.js files.
Getting list of url with ajax call and then use jquery plugin to download multiple files parallel.
$.ajax({
type: "POST",
url: URL,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
async: true,
cache: false,
beforeSend: function () {
blockUI("body");
},
complete: function () { unblockUI("body"); },
success: function (data) {
//here data --> contains list of urls with comma seperated
var listUrls= data.DownloadFilePaths.split(',');
listUrls.forEach(function (url) {
$.fileDownload(url);
});
return false;
},
error: function (result) {
$('#mdlNoDataExist').modal('show');
}
});
Here is the way I do that. I open multiple ZIP but also other kind of data (I export projet in PDF and at same time many ZIPs with document).
I just copy past part of my code.
The call from a button in a list:
$url_pdf = "pdf.php?id=7";
$url_zip1 = "zip.php?id=8";
$url_zip2 = "zip.php?id=9";
$btn_pdf = "<a href=\"javascript:;\" onClick=\"return open_multiple('','".$url_pdf.",".$url_zip1.",".$url_zip2."');\">\n";
$btn_pdf .= "<img src=\"../../../images/icones/pdf.png\" alt=\"Ver\">\n";
$btn_pdf .= "</a>\n"
So a basic call to a JS routine (Vanilla rules!).
here is the JS routine:
function open_multiple(base,url_publication)
{
// URL of pages to open are coma separated
tab_url = url_publication.split(",");
var nb = tab_url.length;
// Loop against URL
for (var x = 0; x < nb; x++)
{
window.open(tab_url[x]);
}
// Base is the dest of the caller page as
// sometimes I need it to refresh
if (base != "")
{
window.location.href = base;
}
}
The trick is to NOT give the direct link of the ZIP file but to send it to the browser. Like this:
$type_mime = "application/zip, application/x-compressed-zip";
$the_mime = "Content-type: ".$type_mime;
$tdoc_size = filesize ($the_zip_path);
$the_length = "Content-Length: " . $tdoc_size;
$tdoc_nom = "Pesquisa.zip";
$the_content_disposition = "Content-Disposition: attachment; filename=\"".$tdoc_nom."\"";
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header($the_mime);
header($the_length);
header($the_content_disposition);
// Clear the cache or some "sh..." will be added
ob_clean();
flush();
readfile($the_zip_path);
exit();
<p class="style1">
<a onclick="downloadAll(window.links)">Balance Sheet Year 2014-2015</a>
</p>
<script>
var links = [
'pdfs/IMG.pdf',
'pdfs/IMG_0001.pdf',
'pdfs/IMG_0002.pdf',
'pdfs/IMG_0003.pdf',
'pdfs/IMG_0004.pdf',
'pdfs/IMG_0005.pdf',
'pdfs/IMG_0006.pdf'
];
function downloadAll(urls) {
var link = document.createElement('a');
link.setAttribute('download','Balance Sheet Year 2014-2015');
link.style.display = 'none';
document.body.appendChild(link);
for (var i = 0; i < urls.length; i++) {
link.setAttribute('href', urls[i]);
link.click();
}
document.body.removeChild(link);
}
</script>

Converting an Image DataUrl to Image

I want to take picture using webcam in my java web application.Now to do this i am using Photobooth.js that provide facility to click images in web applications.
Now my problem is that as soon as I click button to take picture I want to save it in my computer with a name say temp.png in a specified folder say C:/MyPictures.But the picture being clicked by using photobooth.js provides a dataUrl of the form :
data:image/png;base64,iVBORw0KGgoAAAANSU and so on a long string.
How can i get image to specified location now?
My code for using photobooth and displaying the clicked image is as follow:
<script type="text/javascript">
$(document).ready(function () {
$('#photo').photobooth().on("image", function (event, dataUrl) {
alert(dataUrl);
$("#gallery").show().html('<img src="' + dataUrl + '" >');
});
});
</script>
In html part :
<div id="photo"></div>
<div id="gallery"></div>
Here is the .js file am using :
https://github.com/WolframHempel/photobooth-js/blob/gh-pages/photobooth_min.js
I got this code to convert dataURL to blob .Can it be helpful in getting me image to particular location ?
function dataURLtoBlob(dataUrl) {
// Decode the dataURL
var binary = atob(dataUrl.split(',')[1]);
// Create 8-bit unsigned array
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
// Return our Blob object
return new Blob([new Uint8Array(array)], {
type: 'image/png'
});
}
Are you just trying to trigger a download of the image? You can download a file in javascript using an anchor element with a download attribute and firing a click event on it. In this case you could set the anchors href to be the dataURL of your image.
function download(dataUrl, filename) {
var download = document.createElement('a');
download.href = dataUrl;
download.target = '_blank';
download.download = filename;
var evt = document.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0,
false, false, false, false, 0, null);
download.dispatchEvent(evt);
}
See this fiddle:
http://jsfiddle.net/edAAe/1/

How to controll size of image?

**css File**
#zDIV_slideShow a {color:#fff;background-color:#fff}
#zDIV_slideShow {display:none;position:absolute;left:0;top:0;width:100%;height:100%;background-position:50% 50%;background-repeat:no-repeat;text-align:center;margin:0;z-index:10IE Mac;}
**js File**
var TJK_gallery;
var TJK_anchor;
var TJK_itemNumber;
var TJK_stage;
var TJK_itemTitle;
var TJK_itemDescription;
var TJK_navPrev;
var TJK_navClose;
var TJK_navNext;
var TJK_zCounter;
var TJK_zImage;
function TJK_Gallery(zElement){
TJK_gallery=zElement;
TJK_anchor = document.getElementById(TJK_gallery).getElementsByTagName("a");
// building the whole thing from scratch starting with the slideshow
// zDIV_slideShow
var zDiv_wrapper = document.createElement('div');
document.getElementsByTagName("body")[0].appendChild(zDiv_wrapper);
zDiv_wrapper.id="zDIV_slideShow";
// zA_previous
var zA_1 = document.createElement('a');
var zImg_1 = document.createElement('img');
zDiv_wrapper.appendChild(zA_1);
zA_1.id = "zA_previous";
zA_1.title = "Previous Slide";
zA_1.href = "#null";
zA_1.appendChild(zImg_1);
zImg_1.src="img/previous.gif";
zImg_1.alt="Previous Slide";
// zA_close
var zA_2 = document.createElement('a');
var zImg_2 = document.createElement('img');
zDiv_wrapper.appendChild(zA_2);
zA_2.id = "zA_close";
zA_2.title = "Back to the Gallery";
zA_2.href = "#null";
zA_2.appendChild(zImg_2);
zImg_2.src="img/close.gif";
zImg_2.alt="Back to the Gallery";
// zA_next
var zA_3 = document.createElement('a');
var zImg_3 = document.createElement('img');
zDiv_wrapper.appendChild(zA_3);
zA_3.id = "zA_next";
zA_3.title = "Next Slide";
zA_3.href = "#null";
zA_3.appendChild(zImg_3);
zImg_3.src="img/next.gif";
zImg_3.alt="Next Slide";
// zA_title
var zA_4 = document.createElement('a');
zDiv_wrapper.appendChild(zA_4);
var zTitle = document.createTextNode("Title");
zA_4.id = "zA_title";
zA_4.appendChild(zTitle);
// zDIV_counter
var zDiv_counter = document.createElement('div');
var TJK_zCounter = document.createTextNode("Keeping track");
zDiv_wrapper.appendChild(zDiv_counter);
zDiv_counter.id="zDIV_counter";
zDiv_counter.appendChild(TJK_zCounter);
// zA_image
var zA_6 = document.createElement('a');
var zImg_6 = document.createElement('img');
zDiv_wrapper.appendChild(zA_6);
zA_6.id = "zA_image";
zA_6.appendChild(zImg_6);
zImg_6.id="zIMG";
// zA_description
var zA_5 = document.createElement('a');
var zDescription = document.createTextNode("Description");
zDiv_wrapper.appendChild(zA_5);
zA_5.id = "zA_description";
zA_5.href = "#";
zA_5.appendChild(zDescription);
for (var x=0,i=TJK_anchor.length;x<i;x++){
TJK_anchor[x].onclick = badabingbadaboum;
// we create fragment identifier to be used to navigate and keep track of the items and we kick start the whole thing
TJK_anchor[x].href = TJK_anchor[x].href+"#"+x;
// we create a container to receive the text links
var zSPAN = document.createElement('span');
TJK_anchor[x].appendChild(zSPAN);
var zTextLink = document.createTextNode(TJK_anchor[x].title);
zSPAN.appendChild(zTextLink);
}
}
function goPrevious() {
TJK_itemNumber = eval(document.getElementById("zA_title").hash.substring(1));
// hiding the button if we are on first slide
if(TJK_itemNumber==1)this.className="transparent";
TJK_navNext.className="nonOpaque";
if(TJK_itemNumber==0){return} // we are at the beginning
TJK_zImage.src = TJK_anchor[TJK_itemNumber-1].href;
TJK_zImage.alt = TJK_itemTitle.firstChild.data;
TJK_itemTitle.href = TJK_anchor[TJK_itemNumber-1].href;
TJK_itemTitle.firstChild.data = TJK_anchor[TJK_itemNumber-1].getElementsByTagName("img")[0].alt;
TJK_itemDescription.firstChild.data = TJK_anchor[TJK_itemNumber-1].title;
// special care for this one in case there is no long description set
if(TJK_anchor[TJK_itemNumber-1].getElementsByTagName("img")[0].longDesc){
TJK_itemDescription.href = TJK_anchor[TJK_itemNumber-1].getElementsByTagName("img")[0].longDesc;
// appendData() breaks IE5 Win
TJK_itemDescription.firstChild.data=TJK_anchor[TJK_itemNumber-1].title+" [more info...]";
TJK_itemDescription.title = "Follow this link for more Information";
TJK_itemDescription.className="noHand";
TJK_itemDescription.style.textDecoration ="underline";
}else{
TJK_itemDescription.className="withHand";
TJK_itemDescription.title="";
TJK_itemDescription.href="#";
TJK_itemDescription.style.textDecoration ="none";
}
// we update the value of the counter in the DIV
var current = eval(document.getElementById("zA_title").hash.substring(1)) + 1;
TJK_zCounter.firstChild.data = "Item #"+current+" out of "+TJK_anchor.length;
}
function goNext() {
TJK_itemNumber = eval(document.getElementById("zA_title").hash.substring(1));
// hiding the button if we are on the last slide
if(TJK_itemNumber==TJK_anchor.length-2)this.className="transparent";
TJK_navPrev.className="nonOpaque";
if(TJK_anchor.length == TJK_itemNumber+1){return} // we are at the end
TJK_zImage.src = TJK_anchor[TJK_itemNumber+1].href;
TJK_zImage.alt = TJK_itemTitle.firstChild.data;
TJK_itemTitle.href = TJK_anchor[TJK_itemNumber+1].href;
TJK_itemTitle.firstChild.data = TJK_anchor[TJK_itemNumber+1].getElementsByTagName("img")[0].alt;
TJK_itemDescription.firstChild.data = TJK_anchor[TJK_itemNumber+1].title;
// special care for this one in case there is no long description set
if(TJK_anchor[TJK_itemNumber+1].getElementsByTagName("img")[0].longDesc){
TJK_itemDescription.href = TJK_anchor[TJK_itemNumber+1].getElementsByTagName("img")[0].longDesc;
// appendData() breaks IE5 Win
TJK_itemDescription.firstChild.nodeValue=TJK_anchor[TJK_itemNumber+1].title+" [more info...]";
TJK_itemDescription.title = "Follow this link for more Information";
TJK_itemDescription.className
="noHand";
TJK_itemDescription.style.textDecoration ="underline";
}else{
TJK_itemDescription.className
="noHand";
TJK_itemDescription.title="";
TJK_itemDescription.href="#";
TJK_itemDescription.style.textDecoration ="none";
}
// we update the value of the counter in the DIV
var current = eval(document.getElementById("zA_title").hash.substring(1)) + 1;
TJK_zCounter.firstChild.data = "Item #"+current+" out of "+TJK_anchor.length;
}
// to make sure users don't follow the link in the title (it is there to be used as a match with the thumbnail that triggered the popup DIV)
function fakeIt() {return false}
// hiding the SlideShow
function hideTJK_stage() {
document.getElementById("zDIV_slideShow").style.height="0"; // IE5 Mac
document.getElementById("zDIV_slideShow").style.overflow="hidden"; // IE5 Mac
document.getElementById("zDIV_slideShow").style.display="none";
// we remove the opacity stuff
document.getElementById("wrapper").className="none";
// we set focus back to the thumbnail that triggered the "popup" DIV
var TJK_itemNumber = eval(document.getElementById("zA_title").hash.substring(1));
TJK_anchor[TJK_itemNumber].focus();
}
function badabingbadaboum() {
TJK_stage = document.getElementById("zDIV_slideShow");
TJK_itemTitle = document.getElementById("zA_title");
TJK_itemDescription = document.getElementById("zA_description");
TJK_navPrev = document.getElementById("zA_previous");
TJK_navClose = document.getElementById("zA_close");
TJK_navNext = document.getElementById("zA_next");
TJK_zCounter = document.getElementById("zDIV_counter");
TJK_zImage = document.getElementById("zA_image").getElementsByTagName("img")[0];
// we do some opacity stuff
document.getElementById("wrapper").className="transparent";
// IE5 Mac (phantom links)
// this.blur();
// this is to reset the fix for IE Mac (see statement in (hideTJK_stage())
TJK_stage.style.height="20%";
TJK_stage.style.display="block";
TJK_zImage.src = this.href.replace(this.hash,"");
TJK_zImage.alt = this.getElementsByTagName("img")[0].alt;
TJK_zImage.onclick = hideTJK_stage;
// "style.cursor" breaks IE5
TJK_zImage.className = "hand";
TJK_zImage.title = "Back to the Gallery";
// the href value we set for this anchor will be used to give focus back to the appropriate thumbnail
TJK_itemTitle.setAttribute("href",this.href);
// since we have a real href value in there we don't want the user to trigger the link
TJK_itemTitle.onclick=fakeIt;
// clicking on the close box will close the popup DIV
TJK_navClose.onclick=hideTJK_stage;
// setting the action for the prev/next links
TJK_navPrev.onclick=goPrevious;
TJK_navNext.onclick=goNext;
// now we can set focus for keyboard users
TJK_navPrev.focus();
// setting the height - mainly for IE - the second one is for IE5
TJK_stage.style.height = (document.documentElement.clientHeight > 0) ? document.documentElement.clientHeight+"px" : document.body.clientHeight+"px";
// setting the width for IE 5 so there is no gap near the scrollbar
if(document.documentElement.clientHeight == 0)TJK_stage.style.width=document.body.clientWidth+"px" ;
// setting the title and description
TJK_itemTitle.firstChild.data = this.getElementsByTagName("img")[0].alt;
TJK_itemDescription.firstChild.data = this.title;
// if there is a long description in there, we use it as href value of the short description and we give it a title to. If there is none we make sure we reset values previously set and we do not let the user follow the "empty" link
if(this.getElementsByTagName("img")[0].longDesc){
TJK_itemDescription.href = this.getElementsByTagName("img")[0].longDesc;
// appendData() breaks IE5 Win
TJK_itemDescription.firstChild.data=this.title+" [more info...]";
TJK_itemDescription.title = "Follow this link for more Information";
}else{
TJK_itemDescription.removeAttribute("href");
TJK_itemDescription.title = "";
}
// we set the starting values for the "counter"
var current = eval(TJK_itemTitle.hash.substring(1)) + 1;
TJK_zCounter.firstChild.nodeValue = "Slide #"+current+" out of "+TJK_anchor.length;
// hiding the button when everything "loads" depending on which slide we are on
// first we reset both buttons in case they have been turned off last time the user left the slideshow
TJK_navNext.className="nonOpaque";
TJK_navPrev.className="nonOpaque";
TJK_itemNumber = eval(document.getElementById("zA_title").hash.substring(1));
if(TJK_itemNumber==0){
TJK_navPrev.className="transparent";
TJK_navNext.className="nonOpaque";
}
if(TJK_itemNumber==document.getElementById(TJK_gallery).getElementsByTagName("a").length-1){
TJK_navNext.className="transparent";
TJK_navPrev.className="nonOpaque";
}
return false;
}
**in jsp**
<ul id="gallery" >
<li><a name="zGallery" href="img/NNG.jpg"><img src="img/noida.png" /></a></li>
<li><img src="img/gurgaon.png" /></li>
<li><img src="img/bhiwadi.png" /></li>
<li><img src="img/sohna.png" /></li>
<li><img src="img/YamunaExpressway.png" width="260" /></li>
</ul>
i am using a image as a link so when you click new image will open on top of current page.
i want to control the size of image.I have high pixel image so it covers all my page even more. So what change or extra code i need to use to control the size of image.....
This is an example for you that I have a div(width:500, height: 300) will contain the image and the image(1000px x 500px) like this:
<div style="width: 500px; height: 300px;" id="container">
<img src="yourUrl" id="image"/>
</div>
In javascript I'll do like this:
document.getElementById('image').onload = function(){
if(this.naturalWidth > this.naturalHeight){
this.style.Width = document.getElementById('container').style.Width + " !important";
this.style.Height = "auto !important";
}
else{
this.style.Height = document.getElementById('container').style.Height + " !important";
this.style.Width = "auto !important";
}
}
You can specify the height and width of an image based on pixels or percentage.
Eg: <img src="image.jpg" style="width: 50%; height: 50%"/>

How to clik on a text in the div

Could any one please help me in selecting the text (en_GW) under a div?
<-div class="x-combo-list-inner" id="cq-gen339" style="width: 253px; height: 300px;">
<-div class="x-combo-list-item x-combo-selected" ext:qtip="">en_GW<-/div><-div>
Note: Below code not working:
driver.findElement(By.className("x-combo-list-item x-combo-selected")).click();
Error
Compound class names are not supported. Consider searching for one class name and filtering the results.
// xpath
driver.findElement(By.xpath("//div[contains(#class, 'x-combo-list-item x-combo-selected')]")).click();
// css selector
driver.findElement(By.cssSelector("div.x-combo-list-item.x-combo-selected")).click();
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
$(txt5).clickToggle(function() {
alert('First handler: ' + $(this).text());
}, function() {
alert('Second handler: ' + $(this).text());
});
i have no of elements if clicking div count will increase. at the same time click other div first will count will be 0 ?

java equivalent of swfobject

looking for a javascript class like swfobject to embed java and have a simple fallback if the user doesn't have java or refuses the security prompt.
thanks,
Josh
You could build one pretty easily.
Have something like a div set up like this:
<div id="java-applet">
Message to user saying that they need Java here
</div>
Then add Java Plugin Detection (builder) to your JavaScript. Then if that returns true, then do something like:
document.getElementById("java-applet").innerHTML = "<applet>stuff here</applet>";
appletobject may work, but I have not used it.
Just embed the applet like you normally do and insert the fallback inside or insert a javascript snippet to remove the object: Besides param, you can add other elements, e.g. paragraphs with text or javascript calling some function to replace the object.
<script type="text/javascript">
function replace_object(x) {
$(x)...
}
</script>
<object x="y" id="some_applet">
<param name="y" value="z">
<p>java not available. some alternative here. <!-- option 1 --></p>
<script type="text/javascript">
replace_object('some_applet'); // option 2
</script>
</object>
This helps!
I got a very strange problem while using applet to do batch file downloading from the server side.
The Ajax request seems conflict with applet request, the applet file downloading interrupted with some socket exception.
The applet works fine under JRE5.0, it might be caused by our recent upgrade to JRE6.0.
<div id="java-applet"></div>
<script>
var t;
function startApplet() {
var attributes = {codebase:'<%=request.getContextPath()%>',
code:'<%=appletClass%>',
archive:'applet/SignedApplet.jar',
width:0,
height:0} ;
var parameters = {para1:'value1',
para2:'value2',
java_arguments:'-Xms64m -Xmx512m'
} ;
var version = '1.6' ;
var buildAppletTag = function() {
var tag = '<applet';
for (var attribute in attributes){
tag += (' ' + attribute + '="' + attributes[attribute] + '"');
}
tag += ">";
for (var parameter in parameters){
tag += '<param name="' + parameter + '" value="' + parameters[parameter] + '"/>';
}
tag += '</applet>';
return tag;
};
document.getElementById("java-applet").innerHTML = buildAppletTag(attributes, parameters, version);
clearTimeout(t);
}
t = setTimeout("startApplet()", 1000); // delayed
</script>

Categories

Resources