div to appear in full screen - html

I am new to html. Can I make a particular div in my web-page appear in fullscreen when I press alt and space keys? This is my code.
<!DOCTYPE html>
<html>
<body>
<p>This is some text.</p>
<div style="color:#0000FF">
<img src="./1.jpg" height="42" width="42">
</div>
</body>
</html>

Use the full-screen pseudo class (for webkit and mozila) :
:-webkit-full-screen {
/* css rules for full screen */
}
:-moz-full-screen {
/* css rules for full screen */
}
See this Mozilla article and this David Walsh article for usage

HTML and CSS provide no means to trigger full screen mode for an element. JavaScript is your only option.
HTML 5 introduces a full screen API for JavaScript. It is still experimental, so you need to use prefixed property names in some browsers and it won't work at all in others.
function makeFullScreen(element) {
if (element.requestFullScreen) {
element.requestFullScreen();
} else if (element.webkitRequestFullScreen) {
element.webkitRequestFullScreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.msRequestFullScreen) {
element.msRequestFullScreen();
}
}
You then just need to bind an event handler to call it.
document.addEventListener('keypress', function (evt) {
if (evt.altKey && evt.keyCode === 32) {
makeFullScreen(document.querySelector('div'));
}
});
Beware of depending on modifier keys though. On my system, alt + space is captured at the OS level (to open Spotlight) so it will never reach the browser.

Related

Enable scrolling touch IE

In my site i have this problem:
I want that all pages is scrollable if the device have a touch display. My site run into IE
I try with apply touch-action pan-y on my principal div but no result.
Add style to head of your html document
<style>.tst{overflow: hidden;}</style>
Add this line in body tag
<body class="tst" onload ="NoScroll()">
//content here
Add this inside script tags
function noScroll() {
var page = document.getElementsByTagName("body")[0];
if ('ontouchstart' in document.documentElement) {
console.log("touch device detected");
page.classList.remove("tst");
}
else{
console.log("desktop mode");
page.classList.add("tst");
}
}

Remove Certain CSS Style from Html Page

I have a Html page which has anchor tag, I Need to remove certain style applied already in html page for anchor tag while the html page is opened throw Iframe.
HTML Content as below:
<html>
<body>
<div>some content<a href="http://www.website.com" name="test1"/> some content </div>
</body>
</html>
I tried as below:
a[name^="test1"]:before{
content:"[prefix text]";
display:inline;
color:red;
}
a[name^="test1"]:after{
content:"suffix text";
display:inline;
color:green;
}
iframe a[name^="test1"]:before{
display:none;
}
iframe a[name^="test1"]:after{
display:none;
}
But inside "iframe" also these styles has been applying.
You have to first detect if your page is rendered inside an iframe and in that case apply an alternative CSS. It' can't be done with vanilla CSS then it has to be done with some JavaScript:
<script type="text/javascript">
function getTopWindow() {
try {
return window.top;
} catch {
// If we can't access window.top then browser is restricting
// us because of same origin policy.
return true;
}
}
function isRendererdInFrame() {
// If top window is null we may safely assume we're in iframe
return window.self !== getTopWindow();
}
function loadCss(location) {
if(document.createStyleSheet) {
document.createStyleSheet('http://server/stylesheet.css');
} else {
var styles = "#import url('" + location + "');";
var newSS=document.createElement('link');
newSS.rel='stylesheet';
newSS.href='data:text/css,'+escape(styles);
document.getElementsByTagName("head")[0].appendChild(newSS);
}
}
</script>
Code to load CSS from JavaScript is from How to load up CSS files using Javascript?.
With all that code you may simply write (even just after that inside <script> block):
var cssToLoad = isRendererdInFrame() ? "iframe.css" : "not-iframe.css";
loadCss("http://server/" + cssToLoad);
Of course same technique can be applied to patch CSS with iframe specific styles:
if (isRenderedInFrame())
loadCss("http://server/iframe-patch.css");
i dont know how to detect if page is opened in iframe or not, but there is one possible(not very nice) workaround, you can set iframe to width which is not commonly used by devices (example 463px) and then set media query for this resolution which apply when content is shown in this iframe. This is really nasty way since its not 100% and i would not recommending that.

How to remove/ignore :hover css style on touch devices

I want to ignore all :hover CSS declarations if a user visits our website via touch device. Because the :hover CSS does not make sense, and it can even be disturbing if a tablet triggers it on click/tap because then it might stick until the element loses focus. To be honest, I don't know why touch devices feel the need to trigger :hover in first place - but this is reality, so this problem is reality as well.
a:hover {
color:blue;
border-color:green;
/* etc. > ignore all at once for touch devices */
}
So, (how) can I remove/ignore all CSS :hover declarations at once (without having to know each one) for touch devices after having them declared?
tl;dr use this: https://jsfiddle.net/57tmy8j3/
If you're interested why or what other options there are, read on.
Quick'n'dirty - remove :hover styles using JS
You can remove all the CSS rules containing :hover using Javascript. This has the advantage of not having to touch CSS and being compatible even with older browsers.
function hasTouch() {
return 'ontouchstart' in document.documentElement
|| navigator.maxTouchPoints > 0
|| navigator.msMaxTouchPoints > 0;
}
if (hasTouch()) { // remove all the :hover stylesheets
try { // prevent exception on browsers not supporting DOM styleSheets properly
for (var si in document.styleSheets) {
var styleSheet = document.styleSheets[si];
if (!styleSheet.rules) continue;
for (var ri = styleSheet.rules.length - 1; ri >= 0; ri--) {
if (!styleSheet.rules[ri].selectorText) continue;
if (styleSheet.rules[ri].selectorText.match(':hover')) {
styleSheet.deleteRule(ri);
}
}
}
} catch (ex) {}
}
Limitations: stylesheets must be hosted on the same domain (that means no CDNs). Disables hovers on mixed mouse & touch devices like Surface or iPad Pro, which hurts the UX.
CSS-only - use media queries
Place all your :hover rules in a #media block:
#media (hover: hover) {
a:hover { color: blue; }
}
or alternatively, override all your hover rules (compatible with older browsers):
a:hover { color: blue; }
#media (hover: none) {
a:hover { color: inherit; }
}
Limitations: works only on iOS 9.0+, Chrome for Android or Android 5.0+ when using WebView. hover: hover breaks hover effects on older browsers, hover: none needs overriding all the previously defined CSS rules. Both are incompatible with mixed mouse & touch devices.
The most robust - detect touch via JS and prepend CSS :hover rules
This method needs prepending all the hover rules with body.hasHover. (or a class name of your choice)
body.hasHover a:hover { color: blue; }
The hasHover class may be added using hasTouch() from the first example:
if (!hasTouch()) document.body.className += ' hasHover'
However, this whould have the same drawbacks with mixed touch devices as previous examples, which brings us to the ultimate solution. Enable hover effects whenever a mouse cursor is moved, disable hover effects whenever a touch is detected.
function watchForHover() {
// lastTouchTime is used for ignoring emulated mousemove events
let lastTouchTime = 0
function enableHover() {
if (new Date() - lastTouchTime < 500) return
document.body.classList.add('hasHover')
}
function disableHover() {
document.body.classList.remove('hasHover')
}
function updateLastTouchTime() {
lastTouchTime = new Date()
}
document.addEventListener('touchstart', updateLastTouchTime, true)
document.addEventListener('touchstart', disableHover, true)
document.addEventListener('mousemove', enableHover, true)
enableHover()
}
watchForHover()
This should work basically in any browser and enables/disables hover styles as needed.
Here's the full example - modern: https://jsfiddle.net/57tmy8j3/
Legacy (for use with old browsers): https://jsfiddle.net/dkz17jc5/19/
2020 Solution - CSS only - No Javascript
Use media hover with media pointer will help you resolve this issue. Tested on chrome Web and android mobile. I known this old question but I didn't find any solution like this.
#media (hover: hover) and (pointer: fine) {
a:hover { color: red; }
}
<a href="#" >Some Link</a>
hover CSS Media Feature to the rescue! Using only CSS, you can override styles when a device does not have hover capabilities.
The following demo is supported by modern touch devices.
/* hover query styles */
a {
color: red;
font-size: 3em;
}
a:hover {
color: blue;
}
#media (hover: none) {
a:link,
a:visited {
color: blue;
text-decoration: none;
border: 0.1em solid currentColor;
padding: 0 0.1em;
}
}
/* used to show if demo browser has hover capabilities */
.detection:before {
content: 'UNKNOWN';
color: red;
}
#media(hover) {
.detection:before {
content: 'YES';
color: green;
}
}
#media (hover: none) {
.detection:before {
content: 'NO';
}
}
<p>Hoverable pointer detected: <span class="detection"></span></p>
<h3>Experiences between device hover capabilities</h3>
<p>If the device has a hover capability, the link below:</p>
<ul>
<li>should be red</li>
<li>should be blue when hovered</li>
</ul>
<p>If the device does not have a hover capability, the link below:</p>
<ul>
<li>should always be blue</li>
<li>should be surrounded by a blue border</li>
</ul>
<p>Link</p>
Note: Keep in mind that since a Surface PC's primary input (capability) is a mouse, it will end up being a blue link, even if it's a detached (tablet) screen. Browsers will (should) always default to the most precise input's capability.
According to Jason´s answer we can address only devices that doesn't support hover with pure css media queries. We can also address only devices that support hover, like moogal´s answer in a similar question, with
#media not all and (hover: none). It looks weird but it works.
I made a Sass mixin out of this for easier use:
#mixin hover-supported {
#media not all and (hover: none) {
&:hover {
#content;
}
}
}
Update 2019-05-15: I recommend this article from Medium that goes through all different devices that we can target with CSS. Basically it's a mix of these media rules, combine them for specific targets:
#media (hover: hover) {
/* Device that can hover (desktops) */
}
#media (hover: none) {
/* Device that can not hover with ease */
}
#media (pointer: coarse) {
/* Device with limited pointing accuracy (touch) */
}
#media (pointer: fine) {
/* Device with accurate pointing (desktop, stylus-based) */
}
#media (pointer: none) {
/* Device with no pointing */
}
Example for specific targets:
#media (hover: none) and (pointer: coarse) {
/* Smartphones and touchscreens */
}
#media (hover: hover) and (pointer: fine) {
/* Desktops with mouse */
}
I love mixins, this is how I use my hover mixin to only target devices that supports it:
#mixin on-hover {
#media (hover: hover) and (pointer: fine) {
&:hover {
#content;
}
}
}
button {
#include on-hover {
color: blue;
}
}
I have encountered the same problem (in my case with Samsung mobile browsers) and therefore I stumbled upon this question.
Thanks to Calsal's answer I found something that I believe will exclude virtually all desktop browsers because it seems to be recognized by the mobile browsers I tried (see screenshot from a compiled table: CSS pointer feature detection table ).
MDN web docs state that
The pointer CSS #media feature can be used to apply styles based on
whether the user's primary input mechanism is a pointing device, and
if so, how accurate it is
.
What I discovered is that pointer: coarse is something that is unknown to all desktop browsers in the attached table but known to all mobile browsers in the same table. This seems to be most effective choice because all other pointer keyword values give inconsistent results.
Hence you could construct a media query like Calsal described but slightly modified. It makes use of a reversed logic to rule out all touch devices.
Sass mixin:
#mixin hover-supported {
/*
* https://developer.mozilla.org/en-US/docs/Web/CSS/#media/pointer
* coarse: The primary input mechanism includes a pointing device of limited accuracy.
*/
#media not all and (pointer: coarse) {
&:hover {
#content;
}
}
}
a {
color:green;
border-color:blue;
#include hover-supported() {
color:blue;
border-color:green;
}
}
Compiled CSS:
a {
color: green;
border-color: blue;
}
#media not all and (pointer: coarse) {
a:hover {
color: blue;
border-color: green;
}
}
It is also described in this gist I created after researching the problem.
Codepen for empirical research.
UPDATE (2018):
As of writing this update, 2018-08-23, and pointed out by #DmitriPavlutin this technique no longer seems to work with Firefox desktop.
UPDATE (2021):
It has been pointed out to me that it seems to work as of Firefox 87.
I'm dealing with a similar problem currently.
There are two main options that occur to me immediately: (1) user-string checking, or (2) maintaining separate mobile pages using a different URL and having users choose what's better for them.
If you're able to use an internet duct-tape language such as PHP or Ruby, you can check the user string of the device requesting a page, and simply serve the same content but with a <link rel="mobile.css" /> instead of the normal style.
User strings have identifying information about browser, renderer, operating system, etc. It would be up to you to decide what devices are "touch" versus non-touch. You may be able to find this information available somewhere and map it into your system.
A. If you're allowed to ignore old browsers, you just have to add a single rule to the normal, non-mobile css, namely: EDIT: Erk. After doing some experimentation, I discovered the below rule also disables the ability to follow links in webkit-browsers in addition to just causing aesthetic effects to be disabled - see http://jsfiddle.net/3nkcdeao/ As such, you'll have to be a bit more selective as to how you modify rules for the mobile case than what I show here, but it may be a helpful starting point:
* {
pointer-events: none !important; /* only use !important if you have to */
}
As a sidenote, disabling pointer-events on a parent and then explicitly enabling them on a child currently causes any hover-effects on the parent to become active again if a child-element enters :hover.
See http://jsfiddle.net/38Lookhp/5/
B. If you're supporting legacy web-renderers, you'll have to do a bit more work along the lines of removing any rules which set special styles during :hover. To save everyone time, you might just want to build an automated copying + seding command which you run on your standard style sheets to create the mobile versions. That would allow you to just write/update the standard code and scrub away any style-rules which use :hover for the mobile version of your pages.
(I) Alternatively, simply make your users aware that you have an m.website.com for mobile devices in addition to your website.com. Though subdomaining is the most common way, you could also have some other predictable modification of a given URL to allow mobile users to access the modified pages. At that stage, you would want to be sure they don't have to modify the URL every time they navigate to another part of the site.
Again here, you may be able to just add an extra rule or two to the stylesheets or be forced to do something slightly more complicated using sed or a similar utility. It would probably be easiest to apply :not to your styling rules like div:not(.disruptive):hover {... wherein you would add class="disruptive" to elements doing annoying things for mobile users using js or the server language, instead of munging the CSS.
(II) You can actually combine the first two and (if you suspect a user has wandered to the wrong version of a page) you can suggest that they switch into/out of the mobile-type display, or simply have a link somewhere which allows users to flop back and forth. As already-stated, #media queries might also be something to look use in determining what's being used to visit.
(III) If you're up for a jQuery solution once you know what devices are "touch" and which aren't, you might find CSS hover not being ignored on touch-screen devices helpful.
try this:
#media (hover:<s>on-demand</s>) {
button:hover {
background-color: #color-when-NOT-touch-device;
}
}
UPDATE: unfortunately W3C has removed this property from the specs (https://github.com/w3c/csswg-drafts/commit/2078b46218f7462735bb0b5107c9a3e84fb4c4b1).
You can use Modernizr JS (see also this StackOverflow answer), or make a custom JS function:
function is_touch_device() {
return 'ontouchstart' in window // works on most browsers
|| navigator.maxTouchPoints; // works on IE10/11 and Surface
};
if ( is_touch_device() ) {
$('html').addClass('touch');
} else {
$('html').addClass('no-touch');
}
to detect the support of touch event in the browser, and then assign a regular CSS property, traversing the element with the html.no-touch class, like this:
html.touch a {
width: 480px;
}
/* FOR THE DESKTOP, SET THE HOVER STATE */
html.no-touch a:hover {
width: auto;
color:blue;
border-color:green;
}
To make the current answer also work in IE11 (if you're still supporting that though):
#media (hover: hover) and (pointer: fine), only screen and (-ms-high-contrast:active), (-ms-high-contrast:none) {
a:hover { color: red; }
}
<a href="#" >Some Link</a>
It was helpful for me: link
function hoverTouchUnstick() {
// Check if the device supports touch events
if('ontouchstart' in document.documentElement) {
// Loop through each stylesheet
for(var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
var sheet = document.styleSheets[sheetI];
// Verify if cssRules exists in sheet
if(sheet.cssRules) {
// Loop through each rule in sheet
for(var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
var rule = sheet.cssRules[ruleI];
// Verify rule has selector text
if(rule.selectorText) {
// Replace hover psuedo-class with active psuedo-class
rule.selectorText = rule.selectorText.replace(":hover", ":active");
}
}
}
}
}
}
This is also a possible workaround, but you will have to go through your css and add a .no-touch class before your hover styles.
Javascript:
if (!("ontouchstart" in document.documentElement)) {
document.documentElement.className += " no-touch";
}
CSS Example:
<style>
p span {
display: none;
}
.no-touch p:hover span {
display: inline;
}
</style>
<p>Tap me<span>You tapped!</span></p>
Source
P.s. But we should remember, there are coming more and more touch-devices to the market, which are also supporting mouse input at the same time.
After going through the previous answers, this worked for me.
This hover will only work for desktops which has hover. And remove if you have any other hover codes for this class/id
#media (hover: hover) {
.toggle-label:hover {
background-color: #69c9ff;
color: #ffffff;
}
}
This might not be a perfect solution yet (and it’s with jQuery) but maybe it’s a direction / concept to work on: what about doing it the other way round? Which means deactivating the :hover css states by default and activate them if a mousemove event is detected anywhere on the document. Of course this does not work if someone deactivated js. What else might speak against doing it this way round?
Maybe like this:
CSS:
/* will only work if html has class "mousedetected" */
html.mousedetected a:hover {
color:blue;
border-color:green;
}
jQuery:
/* adds "mousedetected" class to html element if mouse moves (which should never happen on touch-only devices shouldn’t it?) */
$("body").mousemove( function() {
$("html").addClass("mousedetected");
});
Try this (i use background and background-color in this example):
var ClickEventType = ((document.ontouchstart !== null) ? 'click' : 'touchstart');
if (ClickEventType == 'touchstart') {
$('a').each(function() { // save original..
var back_color = $(this).css('background-color');
var background = $(this).css('background');
$(this).attr('data-back_color', back_color);
$(this).attr('data-background', background);
});
$('a').on('touchend', function(e) { // overwrite with original style..
var background = $(this).attr('data-background');
var back_color = $(this).attr('data-back_color');
if (back_color != undefined) {
$(this).css({'background-color': back_color});
}
if (background != undefined) {
$(this).css({'background': background});
}
}).on('touchstart', function(e) { // clear added stlye="" elements..
$(this).css({'background': '', 'background-color': ''});
});
}
css:
a {
-webkit-touch-callout: none;
-webkit-tap-highlight-color: transparent;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
The dirty way... Not elegant, but the easiest way that can save you.
Remove anything that characterizes the hover.
.your-class:hover:before {
color: blue;
background: linear-gradient(to bottom, rgba(231,56,39,0) 0%, #aaaaaa 100%);
}
#media all and (min-width:320px) and (max-width: 960px) {
.your-class:hover:before {
color: black;
background: transparent;
}
}
If Your issue is when you touch/tap on android and whole div covered by blue transparent color! Then you need to just change the
CURSOR : POINTER;
to
CURSOR : DEFAULT;
use mediaQuery to hide in mobile phone/Tablet.
This works for me.
Use media hover with media pointer will help you resolve this issue.
#media (hover: none) and (pointer: coarse) {
/* Smartphones and touchscreens */
}
Try this easy 2019 jquery solution, although its been around a while;
add this plugin to head:
src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"
add this to js:
$("*").on("touchend", function(e) { $(this).focus(); }); //applies to all elements
some suggested variations to this are:
$(":input, :checkbox,").on("touchend", function(e) {(this).focus);}); //specify elements
$("*").on("click, touchend", function(e) { $(this).focus(); }); //include click event
css: body { cursor: pointer; } //touch anywhere to end a focus
Notes
place plugin before bootstrap.js to avoif affecting tooltips
only tested on iphone XR ios 12.1.12, and ipad 3 ios 9.3.5, using Safari or Chrome.
References:
https://code.jquery.com/ui/
https://api.jquery.com/category/selectors/jquery-selector-extensions/

make an element full screen in the web page

Any idea to make an element in the page full screen?
For example,a div or an img?
With "full screen" I mean that it should take all the space of user's screen,just like when we watch a video with the full screen model. I do not want the task bar/menu bar of the browser window display.
Any idea?
div.fullscreen{
display:block;
/*set the div in the top-left corner of the screen*/
position:absolute;
top:0;
left:0;
/*set the width and height to 100% of the screen*/
width:100%;
height:100%;
background-color:red
}
I have tried the above code,however it is not what I want,it juse take all the space of the browser's content area rather than the user's computer'screen.
HTML elements can't break out of the bounds of the browser document window. The menu and tool bar are outside of the document window (which is a child of the browser window), so you can't "reach" them.
I think the only solution is to trigger full screen mode with JavaScript.
This answer shows how you can do that: How to make the window full screen with Javascript (stretching all over the screen)
There is a relatively new fullscreen JavaScript api which can make an element full screen.
It has to be called as the result of user input to prevent possible abuse, but it's relatively straight-forward to use:
Code from MDN article:
document.addEventListener("keydown", function(e) {
if (e.keyCode == 13) {
toggleFullScreen();
}
}, false);
function toggleFullScreen() {
if (!document.fullscreenElement && // alternative standard method
!document.mozFullScreenElement && !document.webkitFullscreenElement) { // current working methods
if (document.documentElement.requestFullscreen) {
document.documentElement.requestFullscreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen();
} else if (document.documentElement.webkitRequestFullscreen) {
document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.cancelFullScreen) {
document.cancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
}
}
}
This is not possible now, and it will probably never be.
Just imagine what would happen if every website you visit had free reign to take over your desktop.
In order to do this, you can use the screen.availWidth and screen.availHeight properties to get the screen size. Next, set the element size to their corresponding properties in js.

Print when textarea has overflow

I have a form with some text areas that allow a scroll bar when the text exceeds the text box. The user would like to be able to print the screen, and this text is not visible. How do I make all of the text visible for just printing? Am I better of making a print to pdf link or something?
You cannot solve this problem with CSS alone.
Why Pure-CSS Solutions are Insufficient (with demo)
Let me convince you the answers involving print stylesheets and overflow: visible are insufficient. Open this page and look at the source. Just what they suggested, right? Now print preview it (in, say, Chrome 13 on OS X, like me). Note that you can only see a line or two of the note when you attempt to print!
Here’s the URL for my test case again: https://alanhogan.github.io/web-experiments/print_textarea.html
Solutions:
A JavaScript link that opens a new window and writes the contents of the textarea to it for printing. Or:
When the textarea is updated, copy its contents to another element that that his hidden for screen but displayed when printed.
(If your textarea is read-only, then a server-side solution is also workable.)
Note that textareas treat whitespace differently than HTML does by default, so you should consider applying the CSS white-space: pre-wrap; in the new window you open or to your helper div, respectively. IE7 and older do not understand pre-wrap however, so if that is an issue, either accept it or use a workaround for them. or make the popup window actually plain text, literally served with a media type text/plain (which probably requires a server-side component).
The “Print Helper” Solution (with code + demo)
I have created a demo of one JavaScript technique.
The core concept is copying the textarea contents to another print helper. Code follows.
HTML:
<textarea name="textarea" wrap="wrap" id="the_textarea">
</textarea>
<div id="print_helper"></div>
CSS (all / non-print):
/* Styles for all media */
#print_helper {
display: none;
}
CSS (print):
/* Styles for print (include this after the above) */
#print_helper {
display: block;
overflow: visible;
font-family: Menlo, "Deja Vu Sans Mono", "Bitstream Vera Sans Mono", Monaco, monospace;
white-space: pre;
white-space: pre-wrap;
}
#the_textarea {
display: none;
}
Javascript (with jQuery):
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($){
function copy_to_print_helper(){
$('#print_helper').text($('#the_textarea').val());
}
$('#the_textarea').bind('keydown keyup keypress cut copy past blur change', function(){
copy_to_print_helper(); // consider debouncing this to avoid slowdowns!
});
copy_to_print_helper(); // on initial page load
});
</script>
Again, the successful JavaScript-based demo is at https://alanhogan.github.io/web-experiments/print_textarea_js.html.
Loop through each of your text areas and move the content to a holder
window.onbeforeprint = function () {
$('.print-content').remove();
$('textarea').each(function () {
var text = $(this).val();
$(this).after('<p class="well print-content">' + text + '</p>');
});
}
And use the following CSS
.print-content {
display: none !important;
}
#media print {
.print-content {
display: block !important;
}
textarea {display: none !important;}
}
I recently ran into the same issue. My solution was to duplicate the content into form controls for editing and into divs for printing.
In my Head I put a print stylesheet.
<link rel="stylesheet" href="printform.css" type="text/css" media="print" />
In printform.css I put the following
.screenOnly { display: none; }
.printOnly { display: inline-block; }
For textareas (and other field types that were causing problems) I used the following code
<textarea class="screenOnly" name="myTextArea"><?php echo (htmlspecialchars ($_POST ['myTextArea'])); ?></textarea>
<div class="printOnly"><?php echo (htmlspecialchars ($_POST ['myTextArea'])); ?></div>
When displayed on screen the textareas are shown and the divs duplicating their content are hidden. When printing the opposite applies.
I know you already picked an answer to this question but while using the print stylesheet is a good idea it didn't describe a specific solution. Setting overflow:visible on the textarea (my first idea) didn't work so I ended up going with the solution above. If you're still having difficulties I hope this helps you out
Just encourter the problem recently too. Thanks for Alan H's posts. It works perfect with Chrome and Safari. However, with IE and Firefox, the issue is that the last several pages(page elements after textarea) will be missing from printing(FF), missing pages and overlapped layout(IE9).
Another finding that will be helpful to solve the issue is, you can set textarea's rows properties correctly as the control's height says to make it work with CSS overflow:visable stuff. All browsers seems to respect the rows property while printing.
This seems to work for applying to all elements that have overflowing content:
$("textarea").each(function () {
var Contents = $(this).val();
if ($(this)[0].scrollHeight > $(this).height()) {
$(this).after("<div class='print-helper'>" + Contents + "</div>");
$(this).addClass("no-print");
}
});
This is an easy fix with CSS, given that most users aren't really bothered about printing a bit of extra blank space. Just target a minimum height for textareas when printing:
#media print {
textarea {
min-height: 500px;
}
}
Tag that onto the end of your CSS with a min-height that is comfortably enough when you look at it in Print Preview.
With the usage of pure CSS it is not possible to prepare the textarea for printing.
It is necessary to add some javacript magic to the text area or add a hidden field.
There are a couple of solutions, that have been mentioned here:
Hidden paragraph or div
Using Javascript to extent the size of the textarea
1. Hidden paragraph or div
HTML & CSS:
<textarea>Sample Text</textarea>
<div class="hidden-div">Sample Text</div>
<style>
.hidden-div{display: none;}
#media print{
.hidden-div{display:block;}
}
</style>
2. Javascript
You could use a js library e.g https://github.com/thomasjo/jquery-autoresize
$(function() {
$("textarea").autoResize()
})
Adding onto Alan's answer above, if you have multiple instances of this problem on the same page, then you can use data-* attributes to handle all at once. Sample:
var $printOnlyArr = $('.print-only');
for (var i = 0; i < $printOnlyArr.length; i++) {
var $printOnly = $($printOnlyArr[i]);
var textSource = $printOnly.data('textsource');
if (textSource) {
$printOnly.text($("#" + textSource).val());
}
}
.print-only {
display: none;
}
#media print {
.print-only {
display: block;
}
.no-print {
display: none;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="form-control no-print" maxlength="2000" id="txtAdditionalComments"></textarea>
<div class="print-only" data-textsource="txtAdditionalComments"></div>
I had this same problem. My project is React, I was a semnaticUi TextArea component. The Text that could only be seen by scrolling down in the Textarea aka the "overflow" could not be seen in the print view when I press the print screen button.
Solution :)
I just used a normal paragraph tag instead and set css white-space: pre-wrap on a div that enclosed the p tag.
Worked for me!
try this using jQuery. Redefine height of all textareas based on quantity of lines.
Attention: this code change the textarea on screen too
window.onbeforeprint = function () {
$('textarea').each(function () {
var lines = Math.round($(this).val().split('\n').length * 1.6) ; //multiply to 1.6 to consider spacing between lines
$(this).height(lines+'em');
});
}
Define a separate CSS for print media like this <link rel="stylesheet" href="print.css" type="text/css" media="print" /> and for the text area, define the overflow attribute as
overflow: visible;
I use this in my styling:
PRE.print {
display:none;
}
#media print {
TEXTAREA {
display:none;
}
PRE.print {
display:block;
width:90%; /* fixes margin issues in some funky browsers */
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
font-family:monospace,sans;
}
}
Then, after every TEXTAREA, I use a PRE with class "print" like so:
<textarea id="message" name="message" rows="10" cols="80" onblur="updatePrint('#message')"><?= $MESSAGE ?></textarea>
<pre id="message-print" class="print">
<?= $MESSAGE ?>
</pre>
...note the PHP I used -- you can switch with your programming language. And then this code above needs the following function, assuming you have jQuery library loaded:
<script type="text/javascript">
function updatePrint(sID) {
$(sID + '-print').text($(sID)[0].value);
}
</script>
The way this all works
The way this works is that I'm basically loading content twice into the page, but using the stylesheet to hide content not suitable for the printer like the TEXTAREA.
You can change the PRE styling as you wish. However, I use monospace in case someone was wanting to print HTML code that they typed into the field and wanted it to format nicely.
The onblur event helps capture a need to update the related PRE.
Note you can also do the stylesheet stuff via the media attribute on a link rel in the HEAD section of your HTML, using things like media="all not print" and media="print".