I found the following JS online, which functions like:
If an image is clicked, open the image in new window and prompt for print. Once printed the window closes. I need this script modified to click a print link it prints an image then closes the new image window. So I want to change from clicking the image itself to clicking a link that says print image.
Here is the code:
<script type="text/javascript">
/* <![CDATA[ */
function makepage(src)
{
// We break the closing script tag in half to prevent
// the HTML parser from seeing it as a part of
// the *main* page.
return "<html>\n" +
"<head>\n" +
"<title>Temporary Printing Window</title>\n" +
"<script>\n" +
"function step1() {\n" +
" setTimeout('step2()', 10);\n" +
"}\n" +
"function step2() {\n" +
" window.print();\n" +
" window.close();\n" +
"}\n" +
"</scr" + "ipt>\n" +
"</head>\n" +
"<body onLoad='step1()'>\n" +
"<img src='" + src + "'/>\n" +
"</body>\n" +
"</html>\n";
}
function printme(evt)
{
if (!evt) {
// Old IE
evt = window.event;
}
var image = evt.target;
if (!image) {
// Old IE
image = window.event.srcElement;
}
src = image.src;
link = "about:blank";
var pw = window.open(link, "_new");
pw.document.open();
pw.document.write(makepage(src));
pw.document.close();
}
/* ]]> */
</script>
<img src="fortune.jpg" onclick="printme(event)" />
I do not know any JS so I apologize. I only do php/mysql.
Best Regards!
Jim.
<img src="someurl.jpg" id="imgid' />
Print the image
function printme(id)
{
var src = document.getElementById(id).src;
var link = "about:blank";
var pw = window.open(link, "_new");
pw.document.open();
pw.document.write(makepage(src));
pw.document.close();
}
In the old method, the printme function knows what image should be printed: the same image that was clicked; when you change the trigger, you need to tell the function explicitly what image you want to print. That is why we are adding an id to the image and pass it to printme function. But if you only have one image on the page, or if a spacial relation exists (like the link always being the immediate next node after the image), then we can do it differently and need no id.
I don't know what your link looks like, but assuming it's just a plain anchor:
Change from:
<img src="fortune.jpg" onclick="printme(event)" />
To:
<img id="printableImage" src="fortune.jpg" onclick="printme(event)" />
<a href="javascript:void(0);" onclick="printme('printableImage')" />
Then alter the printme() function to retrieve the image src from the passed in image element id (jQuery makes this easy):
function printme(printableImageId)
{
var src = $('#' + printableImageId).attr('src');
// the rest of the logic...
}
You'll need to modify the printMe function a bit, doing this should fix it:
function printme(evt)
{
if (!evt) {
// Old IE
evt = window.event;
}
var anchor = evt.target;
if (!anchor) {
// Old IE
anchor = window.event.srcElement;
}
src = anchor.href;
link = "about:blank";
var pw = window.open(link, "_new");
pw.document.open();
pw.document.write(makepage(src));
pw.document.close();
return false;
}
And then on your actual anchor you would do the following:
Print
Related
I've made a javascript function to display a number of images in a folder one after another. I'd like to automatically reset my counter if the next image doesn't exist. Eliminating the necessity of passing the number of images in a folder to the function.
<!DOCTYPE html>
<html>
<title>Slideshow</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</html>
<body>
<div id="output" class="slides"></div>
<script type="text/javascript">
var pageURL = window.location.search.substring(1);
var pic_info = pageURL.split('?');
var pic_path = pic_info[0] + '/';
var pic_max_number = 3;
var pic_number = 0;
pic_slideshow();
function pic_slideshow() {
pic_number++;
if (pic_number > pic_max_number) {
pic_number = 1
}
document.getElementById('output').innerHTML = '<img src="' + pic_path + pic_number + '.jpg">';
setTimeout(pic_slideshow, 3000); // Change image every 3 seconds
}
</script>
</body>
</html>
I'D like to add an error handling function, that resets the pic_number variable to 1 to restart the loop. Any ideas using pure javascript?
Thanks...
You can use the onerror attribute of the image tag to reset the global variable pic_number to 1, and load image 1.jpg in place of the missing image.
Change your innerHTML value to:
document.getElementById('output').innerHTML =
'<img src="' + pic_path + pic_number + '.jpg"'
+ ' onerror="pic_number=1; this.src=\'' + pic_path + '1.jpg\'">';
If you add an event listener in your Javascript code you'll need to modify how you're updating your pics.
In your HTML add an img tag:
<div id="output" class="slides"><img src=""></div>
And in your script body add the onerror event listener to that img element:
document.querySelector('#output img').onerror = function (evt) {
pic_number = 1;
evt.target.src = pic_path + '1.jpg';
}
And in your pic_slideshow function change the src value of the existing image element rather than creating a new one:
document.querySelector('#output img').src = pic_path + pic_number + '.jpg';
An event listener will get lost each time you change the #output div innerHTML.
Alternatively you can use the addEventListener method:
document.querySelector('#output img').addEventListener('error', function (evt) {
pic_number = 1;
evt.target.src = pic_path + '1.jpg';
})
You could sense onerror in the img element, or add an eventlistener via JavaScript and reset the counter.
See MDN
I am not new to programming (Fortran, Python) but definitively new to javascript. I also apologize for below function having been taken from another Stack Overflow post but that is the best example I found for for helping me understand want I am trying.
I am writing a Reveal.js presentation that shall show satellite pictures named "sat_picts" + ymd + hr + min + ".jpg"". The pictures are updated every quarter of an hour but it may happen that when they are called the latest one is not yet available so I want to present the one before.
My readings make me understand that this is a characteristic of asynchronous behaviour of the problem and that callback functions are one way of solving the issue.
Unfortunately none of the examples or readings I found show explicitely how to retrieve the results of the callback function in my case "error" and "success". I need these results for an "if, else if" block which then writes in the HTML section the actual or the previous satellite pictures.
I would appreciate if someone could show how to resolve my issue or ev. how to better implement such a solution and or indicate me an appropriate reading.
<section> // Defines Reveal.js slide
<h5>Satellite Picture</h5>
<script>
function testImage(url, callback) {
let img = new Image();
img.onerror = img.onabort = function() {
// callback(url, "error");
let resx = callback(url, "error"); // thought was way to access resx i.e. "error"
alert(resx); // alert is working properly
}
img.onload = function() {
callback(url, "success");
let resy = callback(url, "success"); // thought was way to access resy i.e. "success"
alert(resy); // alert is working properly
}
img.src = url;
};
function record(url, result) {
// document.write(url, result); // ==> returns result but not in the Reveal.js HTML Section
return result;
};
let imgurl = "https://server/sat_picts" + ymd + hr + min + ".jpg";
testImage(imgurl, record);
// If the picture can be loaded then write satellite picture to document
if (resy === "success") document.write('<img src="https://server/sat_picts" + ymd + hr + min + ".jpg">')
// If the the picture cannot be loaded then write satellite picture from previous hour to document
else if (resx === "error") document.write('<img src="https://server/sat_picts" + ymd + hr + min_minus_15 + ".jpg">');
</script>
</section>
If I understand what you are trying to do, I think this is what you want:
<section id="targetSection">
<script>
// allow a success and error call back to be passed in as separate args
function testImage(url, successCallback, errorCallback) {
let img = new Image();
img.onerror = img.onabort = function() {
errorCallback();
}
img.onload = function() {
successCallback();
}
img.src = url;
};
// If the picture can be loaded then write satellite picture to document
function. onSuccess() {
// write the new image to the "section"
const img = document.createElement('img');
img.setAttribute('src', "https://server/sat_picts" + ymd + hr + min + ".jpg");
document.getElementById('targetSection').appendChild(img);
}
// If the the picture cannot be loaded then write satellite picture from previous hour to document
function onError() {
// write the new image to the "section"
const img = document.createElement('img');
img.setAttribute('src', "https://server/sat_picts" + ymd + hr + min_minus_15 + ".jpg");
document.getElementById('targetSection').appendChild(img);
}
let imgurl = "https://server/sat_picts" + ymd + hr + min + ".jpg";
// pass the two callbacks to be called on success or error respectively.
testImage(imgurl, onSuccess, onError);
</script>
</section>
I could be wrong about this, but it looks like the error might be the way the img tags are written in the document.write functions. The img tag needs to be closed with a '/' at the end:
<img src="https://server/sat_picts" + ymd + hr + min + ".jpg" />
The other possibility I can think of is a little gotcha in HTML, which is: when the containing element only has an image tag and no other content, then they won't show the image unless they have some dimensions (height, optionally width) associated with them, so you can check your HTML and if necessary add a CSS property to it that gives it some height (and/or width) to see if this is the issue.
e.g.
<div><img src="myImg.jpg" /></div>
would show nothing if the containing div hasn't been given a height (it will automatically span the width of the parent element).
I've got the following script which swaps the source of an image. However currently this happens after the page loads so the user experiences a split second of seeing one picture before it switches to the correct image.
<script>
window.onload = function () {
var winnerName = $("#leaderboard tr td:eq(1)").text().trim();
$("#pictureDiv img").attr("src", "/Content/Images/" + winnerName + ".jpg");
};
</script>
How can I get the image to switch before loading?
Note I've also tried:
<script>
$(function() {
var winnerName = $("#leaderboard tr td:eq(1)").text().trim();
$("#pictureDiv img").attr("src", "/Content/Images/" + winnerName + ".jpg");
});
</script>
but this results in the same thing occurring
Both of the window.onload or jQuery's $(function()... functions are only called when the page is fully loaded.
The closest you could get is to add the function to the images onload handler.
<img src="..." onload="function() {...}">
But I suspect the same will still occur.
If the image's src needs to be set using javascript then you could try dynamically creating the image and adding it in where you need it, using something like the following.
$(function() {
var winnerName = $("#leaderboard tr td:eq(1)").text().trim();
var imgElement = $('<img>').attr("src", "/Content/Images/" + winnerName + ".jpg");
$("#pictureDiv").append(imgElement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pictureDiv"></div>
I want to open a print dialog for a file(docx,pdf,...) via a SharePoint Workflow. There I call a URL with GET and pass the URL of the file after the ? like this:
http://www.sharepoint_intranet.com/print.html?link-to-file.pdf
EDIT: I also tried:
<script type="text/javascript">
//Get the URL of the file
var urlOfFile = window.location.search.replace("?", "");
document.write("<iframe id=" + "printDocument" + " src=" + "'" + urlOfFile + "'" + " width=" + "600" + " height=" + "400" + "></iframe>");
window.frames['printDocument'].focus();
window.frames['printDocument'].print();
</script>
The Print Dialog is opening and in the print options there is the Point "Only selected Frame" selected but when I press the print button nothing will happen.
Thanks for any help!
you can put in the body of the html
<body onLoad="window.print();">
so the page is opened already prints the document.
The issue is that the new url doesn't start loading until the current script block has finished executing. Therefore when you call w.print(), the new window is currently blank.
Try:
<script type="text/javascript">
//Get the URL of the file
var urlOfFile = window.location.search.replace("?", "");
//print
var w = window.open(urlOfFile);
w.onload = function() {
w.print();
}
</script>
EDIT: I didn't read the question properly! The above technique only works for html. The way to solve this is to use an iframe and if we are using an iframe we might as well dispense with the popups entirely. The following code creates an iframe with a source set to the desired document, attaches the iframe to the page (but keeps it invisible), prints the contents of the iframe and finally removes the iframe once we've finished with it. Only tested in Chrome but I'm fairly confident that it'll work in other browsers.
<script type="text/javascript">
//Get the URL of the file
var urlOfFile = window.location.search.replace("?", "");
//print
var iframe = document.createElement('iframe');
iframe.src = urlOfFile;
iframe.style.display = "none";
var iFrameLoaded = function() {
iframe.contentWindow.print();
iframe.parentNode.removeChild(iframe);
};
if (iframe.attachEvent) iframe.attachEvent('onload', iFrameLoaded); // for IE
else if(iframe.addEventListener) iframe.addEventListener('load', iFrameLoaded, false); // for most other browsers
else iframe.onload = iFrameLoaded; // just in case there's a browser not covered by the first two
window.onload = function() {
document.body.appendChild(iframe);
};
</script>
where we can give the path of the file like("abc.doc"/"abc.xls")
var urlOfFile = window.location.search.replace("?", "");
I have made some custom functionality to the CKEditor. In short, it shows a div tag with 5 links, for Small, Medium, Large X-Large and Original size.
When I click the links, it changes the SRC attribute of the image to the correct size.
It works, but it doesn't persist back to the editor. It's like the Image i get through the click event target, is not part of the Source code.
How can I change the Source code, when manipulating with the elements in the editor?
My code looks like this:
$(target).ckeditor(function (editor) {
$(this.document.$).bind("click", function (event) {
var target = $(event.target);
if (target.is("img")) {
var p = $("<div contenteditable='false' class='image-properties'>" + Milkshake.Resources.Text.size + ": <a class='sizeLink' href='#size1Img'>S</a> <a class='sizeLink' href='#size2Img'>M</a> <a class='sizeLink' href='#size3Img'>L</a> <a class='sizeLink' href='#size4Img'>XL</a> <a class='sizeLink' href='#size5Img'>Org.</a></div>");
p.css("top", target.position().top);
var regex = new RegExp(/(size\d{1}img)/i);
var match = regex.exec(target.attr("src"));
if (match != null) {
var imgSrize = match[0];
p.find("a[href=#" + imgSrize + "]").addClass("selected");
}
p.delegate("a", "click", function (e) {
var link = $(e.target);
if (!link.is(".selected")) {
$(".selected", link.parent()).removeClass("selected");
link.addClass("selected");
var imageSrc = target.attr("src");
imageSrc = imageSrc.replace(/(size\d{1}img)/i, link.attr("href").substring(1));
target.attr("src", imageSrc);
target.css("width", "");
target.css("height", "");
}
e.preventDefault();
});
p.insertAfter(target);
} else if (!target.is("div.image-properties")) {
$("div.image-properties", target.parent()).remove();
}
});
The src of images and href of links are protected in CKEditor to avoid browser bugs (when copying, dragging or sometimes even just loading the content), so you must update also this custom attribute:
data-cke-saved-src