Adding a picture to a html printout using javascript - javascript

I have a sharepoint webpart I am printing using the script below.
The problem is I need to add a a picture to the header of the page it prints that is located at an address. I am trying to modify this but I don't have alot of javascript experience not sure what the syntax is.
Also I would like to specify the image to a specific size and center it is that possible?
I am aware the src is set to "url" I just don't want to share my actual link on here.
<center>
<input onclick="javascript:void(PrintWebPart())" type="button" value="Print Proof of Pricing"/>
</center>
<script language="JavaScript">
//Controls which Web Part or zone to print
var WebPartElementID = "ctl00_ctl34_g_db6615a7_4c3b_4a14_9bbc_43ce9d63c24d_FormControl0";
var d= new Date();
var elem = document.createElement("img");
elem.setAttribute("src", "url");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Tag");
elem.setAttribute("align", "middle");
//Function to print Web Part
function PrintWebPart()
{
var bolWebPartFound = false;
if (document.getElementById != null)
{
//Create html to print in new window
var PrintingHTML = '<HTML>\n<HEAD>\n';
//Take data from Head Tag
if (document.getElementsByTagName != null)
{
var HeadData= document.getElementsByTagName("HEAD");
if (HeadData.length > 0)
PrintingHTML += HeadData[0].innerHTML;
}
PrintingHTML += '\n</HEAD>\n<BODY>\n';
var WebPartData = document.getElementById(WebPartElementID);
if (WebPartData != null)
{
PrintingHTML +='<div id="imageDiv">\n</div>\n'
PrintingHTML += WebPartData.innerHTML;
PrintingHTML += "Pricing Date: " +d;
bolWebPartFound = true;
}
else
{
bolWebPartFound = false;
alert ('Cannot Find Web Part');
}
}
PrintingHTML += '\n</BODY>\n</HTML>';
//Open new window to print
if (bolWebPartFound)
{
var PrintingWindow = window.open("","View Proof of Pricing",
"toolbar,width=800,height=600,scrollbars,resizable,menubar");
PrintingWindow.document.open();
PrintingWindow.document.write(PrintingHTML);
PrintingWindow.document.getElementById("imageDiv").appendChild(elem);
// Open Print Window
}
}
</script>

I believe you can set the image as background to "imageDiv" as
document.getElementById("imageDiv").style["background"]="url(***YOUR_URL***) no-repeat center center";
Note: You do need to give a height to the container as per your need, say
document.getElementById("imageDiv").style["min-height"]="300px";

Related

Display different logo on website depending on date

I've been trying to display a different logo on my website depending on the date (to add a christmas logo that will automatically be displayed in december).
Here's what I've got for now:
<img class="logo" id="global_logo" style="height:56%; margin-top:12px;" src="">
<script>
function initLogo(){
var GlobalDate = date.getMonth()+1;
var GlobalLogo = document.getElementById("global_logo");
if (GlobalDate == 12) {
GlobalLogo.src = "xmas_mgmods-animated.gif"
}else{
GlobalLogo.src = "logo1.png"
}
/**/
alert('Script working');
}
initLogo();
</script>
I've got two problems: first, the logo is not showing up at all (no logo is)
Second: I want to know if I can set the script to also change the style applied for each logo (the style="height:56%; margin-top:12px;"is only needed for the gif, and not for the png).
I've tried to add a line instead of changing the source depending of the ID:
function initLogo(){
var GlobalDate = date.getMonth()+1;
var content = document.getElementById("global_logo");
var GlobalIcon = "";
if (GlobalDate == 12) {
html += "<img class='logo' src='logo1.png'>";
}else{
html += "<img class='logo' style='height:56%; margin-top:12px;' src='xmas_mgmods-animated.gif'>";
}
content.innerHTML += GlobalIcon;
alert('Script working');
}
It doesn't work...
You were using date without having it defined anywhere, assuming you copied it from somewhere else; it was supposed to be an instance of Date.
function initLogo(){
const date = new Date();
var GlobalDate = date.getMonth()+1;
var GlobalLogo = document.getElementById("global_logo");
if(GlobalDate == 12) {
GlobalLogo.innerHTML = `<img class="logo" src="xmas_mgmods-animated.gif" style="height:56%; margin-top:12px;">`;
}
else {
GlobalLogo.innerHTML = `<img class="logo" src="logo1.png">`;
}
}
initLogo();
<div id="global_logo"></div>

Only show one image when displaying image with javascript

I am using this code to show a preview of an image URL.
<input name="input_19" id="input_2_19" type="text" value="" class="medium" placeholder="http://" aria-invalid="false">
<script>
jQuery('#input_2_19').blur(function() {
var src = jQuery(this).val();
var previews = jQuery(".previewImage");
var drawPreview = true;
var PreviousSource = jQuery(this).data('previousSource');
if(!src.match("^https?://(?:[a-z\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png|jpeg)$") && src != "")
{
jQuery("#warning").html("Must be an image");
return false;
} else {
jQuery("#warning").html("");
}
jQuery.each(previews , function(index, value) {
if (src == "" && PreviousSource == $(value).attr('src'))
{
jQuery(value).remove();
drawPreview = false;
return false;
}
if( jQuery(value).attr('src') == src)
{
drawPreview = false;
return false;
}
});
if(drawPreview) {
jQuery('#prev').append('<img class="previewImage" style="max-width:500px;" src="' + src + '">');
}
var previousSource = jQuery(this).data('previousSource', src);
});
</script>
<div id="warning"></div>
<div id="prev"></div>
It works well, but if I change the image URL then the second image will show up too and the first will stay.
How do I make it so only one image preview is shown?
https://jsfiddle.net/LucyTech/qohxryL4/4/
Also why doesn't it work with some images eg
https://ae01.alicdn.com/kf/HTB1q0ucSYrpK1RjSZTEq6AWAVXap/Mifa-Portable-Bluetooth-speaker-Portable-Wireless-Loudspeaker-Sound-System-10W-stereo-Music-surround-Waterproof-Outdoor-Speaker.jpg
what is wrong with this url? In the browser it shows an image so why does the code give an error?
Please use this javascript. That will give you result as per your expectation.
$('#input_2_19').blur(function() {
console.log(jQuery(this).val());
var src = jQuery(this).val();
var previews = $(".previewImage");
var drawPreview = true;
var PreviousSource = $(this).data('previousSource');
if(src.match("/\.(jpeg|jpg|gif|png)$/") != null && src != "")
{
$("#warning").html("Must be an image");
return false;
} else {
$("#warning").html("");
$('#prev').html('<img class="previewImage" style="max-width:50px;" src="' + src + '">');
}
});
Using append() will always add a new element. Maybe you should include the img tag in the initial html with its own id property and change its src property with attr(). You can use show() and hide() on an image element or you can wrap it in a div/span and hide this one.
Before appending the
below code should work.
jQuery('#prev').html('');
After this add your img tag
jQuery('#prev').html('<img class="previewImage" style="max-width:500px;" src="' + src + '">');
The problem of the image not previewing for some the links I think is related to the regular expression that you wrote in the str.math I am not very good in so I can not help you with it but I took a look at your post's first comment "Jinesh", his/her regular expression seems to work. For the other problem, I wrote some piece of code for with comments to fix the the multiple image
// When you release the keyboard key
$("#urlInput").keyup(function(){
$("#warning").text(""); // Clear message div
var url = $("#urlInput").val(); // get url in the input box
if(isValidImageUrl(url)) // Validate the url
$("#prevImg").attr("src", url).show(); // Change src of th eimg tag and Show it
else
$("#prevImg").attr("src", "").hide(); // If the url is not valid, hide the img tag in the html
});
// When you get out the side the input box such as clicking outside or pressing tab key
$("#urlInput").blur(function(){
var url = $("#urlInput").val(); // Get the url in the input box
if(!isValidImageUrl(url)) // Validate the url
$("#warning").text("Must be an image"); // if the url is invalid show warning
});
// Valdiate url fucntion
function isValidImageUrl(checkUrl){
return checkUrl.match("^https?://(?:[a-z\-]+\.)+[a-z]{2,10000}(?:/[^/#?]+)+\.(?:jpg|gif|png|jpeg)$");
}
img{
width: 100px;
height: 100px;
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="warning"></div>
<input id="urlInput">
<div id="prev">
<img id="prevImg">
</div>

What is the best way to change images based on the last 3 characters on the URL?

What is the best way to change images based on the last 3 characters on the URL?
I have 3 pictures but when click - needs to stay as the selected image,
but the page refreshes and goes back to original image
<script type="text/javascript">
function image_swap() {
var URLChar = $(location).attr('href').charAt($(location).attr('href').length - 3)
if (URLChar("NSW"); image.src = "../MCFILES/NSW1.jpg"
if (URLChar("VIC"); image.src = "../MCFILES/VIC1.jpg"
if (URLChar("QLD"); image.src = "../MCFILES/QLD1.jpg"
} else {
image.src = "../MCFILES/NSW1.jpg"
}
}
function newDocNSW() {
var CurrentURL = window.location.href;
var OriginalURL = CurrentURL.replace(/\&.*/, '');
window.location.assign(OriginalURL + "&St=NSW");
}
function newDocQLD() {
var CurrentURL = window.location.href;
var OriginalURL = CurrentURL.replace(/\&.*/, '');
window.location.assign(OriginalURL + "&St=QLD");
}
function newDocVIC() {
var CurrentURL = window.location.href;
var OriginalURL = CurrentURL.replace(/\&.*/, '');
window.location.assign(OriginalURL + "&St=VIC");
}
</script>
<body>
This is the images i need to change when on hover and when click
runs another script to change URL.
When the page refreshes i need the option to have change picture
when page refreshes to change the URL
<img id="image_swap" src="../MCFILES/NSWO.jpg"
onclick="newDocNSW()"
onmouseover="this.src='../MCFILES/NSW1.jpg';"
onmouseout="this.src='../MCFILES/NSWO.jpg';">
<img id="image_swap" src="../MCFILES/QLDO.jpg"
onclick="newDocQLD()"
onmouseover="this.src='../MCFILES/QLD1.jpg';"
onmouseout="this.src='../MCFILES/QLDO.jpg';">
<img id="image_swap" src="../MCFILES/VICO.jpg"
onclick="newDocVIC()"
onmouseover="this.src='../MCFILES/VIC1.jpg';"
onmouseout="this.src='../MCFILES/VICO.jpg';">
</body>
</html>
This line will only extract a single character
var URLChar = $(location).attr('href').charAt($(location).attr('href').length - 3 )
If you want the last three characters then use this:
var URLChar = $(location).attr('href').substring($(location).attr('href').length - 3, $(location).attr('href').length);
A much simpler plain/vanilla JavaScript approach would be:
var URLChar = location.href.substring(location.href.length - 3, location.href.length);
Your if conditions are also syntactically incorrect. Here's how it should be:
if (URLChar === "NSW"){
image.src = "../MCFILES/NSW1.jpg";
} else if (URLChar === "VIC"){
image.src = "../MCFILES/VIC1.jpg";
} else if (URLChar === "QLD"){
image.src = "../MCFILES/QLD1.jpg";
} else {
image.src = "../MCFILES/NSW1.jpg";
}
I think this should do if I'm understanding the problem correctly.

Update Title Tag Using Javascript

I've had help from StackOverflow to generate this JavaScript to use in a GreaseMonkey script, which replaces an image with an H1 tag, to use on an Oracle E-Business Suite system where the instance name is held in an H1 tag:
// current page
var url_loc = window.location.href;
if (url_loc.indexOf("http://this.site:0123") == 0) { var env_label = "LIVE";}
if (url_loc.indexOf("http://this.site:1234") == 0) { var env_label = "TEST1";}
if (url_loc.indexOf("http://this.site:2345") == 0) { var env_label = "TEST2";}
if (url_loc.indexOf("http://this.site:3456") == 0) { var env_label = "TEST3";}
if (url_loc.indexOf("http://this.site:4567") == 0) { var env_label = "TEST4";}
if (url_loc.indexOf("http://this.site:5678") == 0) { var env_label = "TEST5";}
var imgs=document.getElementsByTagName('img');
for(var i=imgs.length-1;i>=0;i--){
if(imgs[i].title == 'NEW_UNI_LOGO.png' || imgs[i].title == 'Oracle') {
var h1 = document.createElement('h1');
h1.innerHTML = env_label;
imgs[i].parentNode.insertBefore( h1, imgs[i] );
imgs[i].parentNode.removeChild(imgs[i]);
h1.style.color = "red";
}
}
It would be really useful to also update the Title tag on the page to start with the env_label value. I don't want to replace all of the content of the Title tag, so that e.g. if the Title is:
<title>Oracle Applications Home Page</title>
I'd like to change it to e.g. for the Live Site:
<title>LIVE: Oracle Applications Home Page</title>
Basically just append env_label to the start of whatever is held in the title tag.
Thanks
Try this..
document.title = "Oracle Applications Home Page";
Appending the label to the title..
document.title =env_label + ": Oracle Applications Home Page";
Did you even try something before asking to it ? I can't think about a more simple problem ...
document.title = env_label + ": " + document.title;

use javascript to insert google ads within a page of text

I am trying to insert google ads after the first paragraph of the text box on my mediawiki site. My code is based on https://www.mediawiki.org/wiki/Extension:AdsWherever.
I have a function that returns a tag which will render the google ads code.
I am using javascript to check if the tag is there, if it isn't I'm inserting it after the first paragraph.
The issue is none of the rest of the text in the text box is showing after the google ads. I think this may because the function is returning a value and breaking out of the code and so not allowing the rest of the javascript code to run. (I may be wrong but this is what I think the issue is).
How do I insert the google ads in the correct place and still show the text after the ads?
I don't mind skipping the function altogether and just using javascript to insert the code but I don't know how to write the javascript so var b contains the javascript for the google ads.
This is my code:
$wgHooks['ParserFirstCallInit'][] = 'AdsSetup';
$wgHooks['EditPage::showEditForm:initial'][] = 'CheckHasTag';
function AdsSetup( &$parser ) {$parser->setHook( 'ads', 'AdsRender' ); return true;}
function AdsRender($input, $args ) {
$input =""; $url = array(); global $wgOut;
$ad['goo1'] = '<html><br><script type="text/javascript">
google_ad_client = "xxx";
google_ad_width = 728;
google_ad_height = 90;
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br></html>';
$media = $args['media'];
return $ad[$media];
}
// check if content has <goo1> tag
function CheckHasTag($editPage){
global $wgOut;
$wgOut->addScript('<script type="text/javascript">
var editTextboxText = document.getElementById("wpTextbox1").value;
var searchFor = "goo1";
var searchResult = editTextboxText.search(searchFor);
if(searchResult == -1){
var a = editTextboxText;
var b = "\n<ads media=goo1>\n";
var findP = "\n";
var p = editTextboxText.search(findP);
var position = p;
document.getElementById("wpTextbox1").value = a.substr(0, position) + b + a.substr(position);
}
</script>');
return true;
}
var editTextboxText = document.getElementById("mw-content-text").innerHTML;
var searchFor = new RegExp("goo1");
if (searchFor.test(editTextboxText) === false) {
var ad = document.createElement('ads');
ad.setAttribute('media', 'goo1');
var parent = document.getElementById("mw-content-text").getElementsByTagName('p')[0].parentNode;
var secondParagraph = document.getElementById("mw-content-text").getElementsByTagName('p')[0].nextSibling;
parent.insertBefore(ad, secondParagraph);
}
JSfiddle

Categories

Resources