Printing viewable contents of browser window - javascript

I have a website I am currently developing and the client has a very unique request. They would like the user to be able to hit a button and print the contents of the browser window. I wanted to know if anyone has implemented similar functionality or knows any strategy to develop something like this as I do not have the first clue.
Example: I have 30 images on a page but only 4 fit in the viewable area or browser window. I would like to only print the exact content of the browser window / or elements that are viewable area.
Thanks in advance,
JN

This method requires jQuery, but might be able to be rewritten in plain javascript.
With a bookmarklet app of mine I found that the popup window was the most reliable way to print dynamic content and allowed the user to see the content before printing it. I also found that reducing the font size allowed fitting all the content on the page while sill be readable. You might try shrinking the images as well if that is an option. I had tried targeting media types with CSS and some jQuery print plugins but found them unreliable at best.
Here's the function I use to pass a jQuery object to be printed. I maximized the window on open and changed the title/font size. If you have more than images you'll need to clone your CSS as well, mine just happened to be stored in a variable from the bookmarklet loading.
function printElement(oElement) {
var oPopupWindow = window.open('', 'newwin', 'width=500,height=500');
oPopupWindow.moveTo(0,0);
oPopupWindow.resizeTo(screen.availWidth,screen.availHeight);
oPopupWindow.document.open();
var sHTML = '<html><head><title>TBA Enhanced User Interace</title>' +
_EUI.sCSS + '<style>img {display:none!important}table{font-size:8pt!important}</style></head><body>'
+ $('<div />').append(oElement.clone()).html() + '</body></html>';
oPopupWindow.document.write(sHTML);
oPopupWindow.document.close();
oPopupWindow.print();
oPopupWindow.close();
}
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}
function printVisibleImages() {
var oImageElement = $('<div />');
$('img').each(function() {
if (isScrolledIntoView(this)) {
oImageElement.append(this);
}
});
printElement(oImageElement);
}
Using the isScrolledIntoView function from this question: Check if element is visible after scrolling, something like the code above might work with some tweaking. Call printVisibleImages(), you might need to add some CSS for padding or pass the style sheets from the main page.

You could - in the same or a new window - wrap a DIV around all of the BODYs content and restrict the display area to currently visible . If there's a root-container-DIV for example...
<body>
<div id="theWholeDocument">
... content
</div>
</body>
... it can easily be done by jQuery:
$('#theWholeDocument').wrap( function() {
// get coordinates and dimensions of visible area first
// assing to var prLeft, prTop, prWidth, prHeight
return '<div style="position:absolute;left:"+prLeft+"px; top:"+prTop+"px; width:"+prWidth+"px; height:"+prHeight+"px; overflow:hidden"/>');
}
Should result in a Document that shows nothing else than what has been visible before. Printout schould look the same, like a screenshot - with propably cropped images at the bottom.

Make a jQuery function that loads a page on the click of a button via Ajax. (sending the page name as a post parameter). In that page, you do this:
$file = file_get_contents($_POST['file']);
echo $file;
and you style accordingly.

Maybe you can play around with Javascript (take a look at how to get window dimensions and scroll positions), but I don't realize how to print only that part of the document...
Maybe this can help you: snapshot from browser with flash or javascript

I have 30 images on a page but only 4 fit in the viewable area or
browser window.
I don't think you can say with certainty that the above works in all situations.
It is quite possible that many other browsers/resolutions will produce man different configurations, including some where the images are chopped off, etc.
The better solution, I think, is to offer X number of images per printed page and style accordingly.

One of the web apps needed something similar to what you are asking for. It is an FAQ link which produced an FAQ page and the user wanted the ability to print it, if they so chose.
I did this by simply adding a button to the html:
<input type="button" value="Print" onClick='window.print();' />
<input type="button" value="Close" onClick='window.close();' />
Because I popped this into its own little browser window, I stripped off all the other controls from the parent page via:
function popFaq() {
window.open('faq.html', '',
'left=10, top=10, width=550, height=700, resizable=1, ' +
'location=0, personalbar=0, scrollbars=1, statusbar=0, toolbar=0, menubar=0');
}
... and ...
<div id='hLink'>
<a title='Click Here for (F)requently (A)sked (Q)uestions' href='' onclick='popFaq(); return false;'>FAQ</a>
</div>
Hope that helps!

Related

How to enforce user must scroll pdf within iframe

I have a pdf file within iframe. I want user to scroll must in pdf file before submitting the form. i am trying with this,
var position = $('#myIframe').contents().scrollTop();
But not working. Please help me Thanks in advance.
If you don't mind making a static height for your iframe, I have a solution for you.
HTML and CSS
1. Wrap your iframe in a div container
2. set heights for both your container and iframe (height of container should be the height you want your frame to be seen and the iframe height should be large enough to show entire pdf.)
3. set container div's overflow to scroll
Now you have a scrollable "iframe".
Javscript
Get container element. (var containerEl = $("#container")[0];)
Write a scroll function. Within the scroll function find if the total height of the element (scrollHeight) is less than or equal to how much has been scrolled (scrollTop) plus the inner height (clientHeight) of the
element. If it is, remove disabled property from button
Here's the fiddle. Made some changes to #mJunaidSalaat's jsfiddle.
Well I've tried almost an hour on this, Researched it, finally coming to a conclusion that Unfortunately this is not possible using this method.
The PDF is usually not a DOM element, it's rendered by PDF reader software. Every browser has its own mechanism for rendering PDFs, there is no standard. In some cases, the PDF might be rendered by PDF.js; in those situations you might be able to detect scrolling. But Adobe Reader, Foxit, and some of the native PDF rendering don't provide that option.
I've also created a Github issue for this. But no use.
Sorry. Please update me if you could find any thing or any workaround.
I've made a Fiddle for your solution. You can disable the submit button for user until user scroll on your iframe.
function getFrameTargetElement(objI) {
var objFrame = objI.contentWindow;
if (window.pageYOffset == undefined) {
objFrame = (objFrame.document.documentElement) ? objFrame.document.documentElement : objFrame = document.body;
}
return objFrame;
}
$("#myIframe").ready(function() {
var frame = getFrameTargetElement(document.getElementById("myIframe"));
frame.onscroll = function(e) {
$('.submitBtn').prop('disabled', false);
}
});
Hope it helps.
try this
$("#myIframe").ready(function() {
var frame = getFrameTargetElement(document.getElementById("myIframe"));
frame.onscroll = function(e) {
$('.submitBtn').prop('disabled', false);
}
});

Chrome ignoring hashes in URL

I've spent quite a while trying to find answers for this issue, but haven't had any success. Basically I need to scroll the user to the contact portion of the website when they go to healthdollars.com/#contact. This works just fine in Safari, but in Chrome I haven't had any luck. I've tried using jQuery/Javascript to force the browser to scroll down, but I haven't been able to.
Does anyone have any ideas? It's driving me crazy - especially since it's such a simple thing to do.
Not a full answer but in Chrome if you disable Javascript I believe you get the desired behavior. This makes me believe that something in your JavaScript is preventing default browser behavior.
It looks to me like the target element doesn't exist when when page first loads. I don't have any problem if I navigate to the page and then add the hash.
if (window.location.hash.length && $(location.hash)) {
window.scrollTo(0, $(location.hash).offset().top)
}
check for a hash, find the element's page offset, and scroll there (x, y).
edit: I noticed that, in fact, the page starts at #contact, then scrolls back to the top. I agree with the other answerer that there's something on your page that's scrolling you to the top. I'd search for that before adding a hack.
You can do this with JS, for example` if you have JQuery.
$(function(){
// get the selector to scroll (#contact)
var $to = $(window.location.hash);
// jquery animate
$('html'/* or body */).animate({ scrollTop: $to.offset().top });
});
The name attribute doesn't exists in HTML 5 so chrome looks to have made the name attribute obsolete when you use the DOCTYPE html.
The other browsers have yet to catch up.
Change
<a name="contact"></a>
to
<a id="contact"></a>
Maybe this workaround with vanilla javascript can be useful:
// Get the HTMLElement that you want to scroll to.
var element = document.querySelector('#contact');
// Stories the height of element in the page.
var elementHeight = element.scrollHeight;
// Get the HTMLElement that will fire the scroll on{event}.
var trigger = document.querySelector('[href="#contact"]');
trigger.addEventListener('click', function (event) {
// Hide the hash from URL.
event.preventDefault();
// Call the scrollTo(width, height) method of window, for example.
window.scrollTo(0, elementHeight);
})

Make Facebook plugin responsive

So I am using the new Facebook plugin (Page Plugin) and have a hard time to get it responsive on window resize.
I have set the option data-adapt-container-width="true", but that only triggers when there i a page load/reload.
Please se my JSFiddle: http://jsfiddle.net/29zgc790/ (try it in exporer and if that dont work try my plunker: http://plnkr.co/edit/IPnjpJUXxkO4WTLFTTW0?p=preview) where i have set the start width for the plugin to max (500px), but I want to trigger a reload of the plugin when the container (window) gets smaller then the plugin at that particular time.
I am thinking about somthing like:
$(window).resize(function () {
//Do the reload of plugin
});
Hope you guys have an idea of an solution that can guid me in the right way.
Embed the iframe generated:
<iframe id="facebook" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" title="fb:page Facebook Social Plugin" src="http://www.facebook.com/v2.5/plugins/page.php?adapt_container_width=true&app_id=&channel=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter%2FTlA_zCeMkxl.js%3Fversion%3D41%23cb%3Df1ce7bfb%26domain%3Drun.plnkr.co%26origin%3Dhttp%253A%252F%252Frun.plnkr.co%252Ff152208424%26relation%3Dparent.parent&hide_cover=true&href=https%3A%2F%2Fwww.facebook.com%2Fmicrosoft&locale=en_US&sdk=joey&show_facepile=false&show_posts=true&small_header=true&width=500"
style="border: none; visibility: visible;width: 500px; height: 500px;" class=""></iframe>
Get parent width and set it into iframe and iframe's src attribute
$(window).resize(function() {
//Do the reload of plugin
var new_width = $("#facebook").parent().width();
$("#facebook").css("width", new_width);
var url = $('#facebook').attr('src').split("&width=");
url = url[0] + '&width=' + new_width;
$('#facebook').attr('src', url);
});
After a few days of trying to achieve this, I came up with a working solution!
I actually registered only to share it :)
Copy the iframe code of the page plugin here:
Facebook Page Plugin (go to "Get code" and then click on "iFrame" on the top of the window that just opened.)
Paste the code to your html inside a div with class fb-column, then remove the width and src attributes (paste the value of the src attribute - the long link - somewhere else, you will need it later)
Add this code to your main .js file (credit for calculating the box size and calling the function goes to Mugo Web
function resizeFBPlugin() {
//calculate parent box width
var container_width = (Number($('.fb-column').width()) - Number($('.fb-column').css('padding-left').replace("px", ""))).toFixed(0);
// set the src and replace the actual width with the calculated width.
document.getElementById("fb-column").src = //paster link from iFrame here. Be sure to keep everything as it is, only replace the number after &width= with container_width
// it should look something like this: 'https://www.facebook.com....&width='+container_width+'&height=......';
// NOTE: take note of the use of apostrophes and + signs
//set the width of the iframe
document.getElementById("fb-column").width = container_width;
};
// call the function on resize and on window load
$(window).on('resize', function() {
setTimeout(function(){resizeFBPlugin()}, 500);
});
$(window).on('load', function() {
setTimeout(function(){resizeFBPlugin()}, 1500);
});
That's it! You now have a fully responsive Facebook page plugin (of course, within the min 180px and max 500px width.
BTW, The Twitter plugin works perfectly. I have no idea why Facebook decided not to fix this... I suppose they don't have the money for the right developers :)
So after reading the documentation for the facebook web sdk I found this little function that reloads the iframe.
FB.XFBML.parse();
https://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse
That solved my problem, but #LucaGiardina hade a good solution as well but I think its always a god practice to use the built in functions if thay exist.
I have found out some solution but i think the best one is at least for me is that setting the parent tag of fb-comment-wrapper in a certain responsive then use facebook built in css data-width:
<div class="fb-comment-wrapper">
<div class="fb-comments" data-href="{{request.build_absolute_uri}}"
data-numposts="3" data-width="100%">
</div>
</div`>

style a JavaScript onmouseover alert

This is my code to make the alert appear when i hover over the image;
var special_offers = document.getElementsByClassName("special_offer");
//for each special offer
for(i=0;i<special_offers.length;i++){
var special_offer = special_offers[i];
special_offer.setAttribute("offer_shown", "0");
special_offer.onmouseover = function(){
if( this.getAttribute("offer_shown") == "0" ){
this.setAttribute("offer_shown", "1");
alert('This room has the special offer attached to it, please book soon before you miss out!');
}
}
I wanted to find out how i change this from the bog standard JS alert to a box that i can style, i imagine i'd use some sort of a div.
Any help is much appreciated.
http://www.webdesignerdepot.com/2012/10/creating-a-modal-window-with-html5-and-css3/
This is a good resource for creating your own modal window. You can use your function to fire the modal window you created instead of just using alert() to fire up the standard alert.
Do you want to direct your message to a div?
Create the div
<div id="mySpecialOffer">
Some Text gets updated
</div>
In your js you could then target this id and update with what ever message you would like.
document.getElementById("mySpecialOffer").innerHTML = 'some Text';
You could even hide the div in css and then unhide with the JS.
Or you can create the HTML...
document.getElementById("mySpecialOffer").innerHTML = '<div> Special Offer Div Inserted </div>';
This is even easier with jQuery.
Is this what you had in mind?
What you should do is open a whole new window, like a small webpage with that message. That would be the easiest way to go!Here is a link: http://www.w3schools.com/jsref/met_win_open.asp
You will want to have the window.open() activated when people mouseover an image.you can specify the size and positioning of the window, in this case the center of the screen, and a small window.
Hope that helps!

Multiple, unique, popup windows with JPopUp script?

I know this has probably been answered multiple times before, but this is the second time I've worked with JQuery, and I'm not entirely sure what I need to do, since I'm not familiar with this format of coding. I've looked at other, similar, questions, but none of the answers are making sense to me, and I really need this to click in my head so I can keep working.
I'm using Jpopup for this, so the script info is all there, but my question is this:
I have two areas in an image that I need to be clickable, both showing different content, but I can only call one page at a time to pop up, and multiple anchor tags just give me the same content twice. What do I need to add to that script to allow the page to show two different popups?
This is the script in my HTML page
<script language="javascript">
$(document).ready(function() {
//Change these values to style your modal popup
var source = "demo.html";
var width = 920;
var align = "center";
var top = 100;
var padding = 10;
var backgroundColor = "#FFFFFF";
var source = 'popups/demo.html';
var borderColor = "#000000";
var borderWeight = 4;
var borderRadius = 5;
var fadeOutTime = 300;
var disableColor = "#666666";
var disableOpacity = 40;
var loadingImage = "popups/loading.gif";
//This method initialises the modal popup
$(".modal").click(function() {
modalPopup( align,
top,
width,
padding,
disableColor,
disableOpacity,
backgroundColor,
borderColor,
borderWeight,
borderRadius,
fadeOutTime,
source,
loadingImage );
});
//This method hides the popup when the escape key is pressed
$(document).keyup(function(e) {
if (e.keyCode == 27) {
closePopup(fadeOutTime);
}
});
});
</script>
The HTML
<div style="margin-top:200px;margin-left:395px;">
<a class="modal" href="javascript:void(0);"><img src="images/clickmelarge.png" border="0">
</a></div>
I studied the source code of the "plugin" and studied also the invoked source code of the HTML page at runtime. In my eyes this popup plugin doesn't support multiple popups at same time. Why?
Well, I used Firebug to exermine the source code at runtime and I saw only the same divs, added to the DOM tree by this. As far as I did understand when the DOM was complete loaded the author added the main divs to the DOM tree and set they all to 'hide'. If you call your function these divs will set to 'visible'.
Another reason is -in my eyes a very tricky way- the div with the Id 'blockModalPopupDiv' covers the full browser window. If you click on this element, the function of hiding all divs will be executed. You won't be have chance to click outside the div element.
So what can you do?
I think you have only three options :
Ask the author for an opportuniti to add your requirement.
Download the source code and modifiy it your self. Its created in standard Javascript.
Try to use another plugin or change your concept.

Categories