how to set different height for different browser? - javascript

I have div that has a height: 300px; and overflow: auto;. It looks good in Chrome, but in Firefox it start scroll the page. When I decrease the height to height: 200px;` it looks good.
Can we give different div height when html page open in Chrome and Firefox?

Use the below CSS block for firefox
#-moz-document url-prefix() {
.selector {
width:200px;
}
}
and use the below CSS block for chrome
#media screen and (-webkit-min-device-pixel-ratio:0) {
.selector {
width:300px;
}
}

You can write browser specific code by detecting browser.
Here is the link for browser detection Browser detection in JavaScript?

Give the condition according to the browser using javascript
if (!!window.chrome == true) {
//condition for chrome
}
else if (typeof InstallTrigger !== 'undefined') {
//condition for firefox
}
else if (/*#cc_on!#*/false == true) {
//condition for safari
}
else if (!!window.opera || navigator.userAgent.indexOf('Opera') >= 0) {
//condition for opera
}
else if (Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
//condition fo IE
}
This javascript code will detect the browser. Give onload function for body and give the code for that function.

I think better way to change the css files based on the browser. As I think it is better to separate the styles functionality from the JavaScript. It will be good coding practice and maintainability will be easier.

Use different styles sheets (css) based on the browser.
E.g.
<script type="text/javascript">
var browser=navigator.appName;
if browser == "Microsoft Internet Explorer"
{
document.write("<link type=\"text/css\" rel=\"stylesheet\" href=\"IE.css\">");
}
else if browser == "Firefox"
{
document.write("<link type=\"text/css\" rel=\"stylesheet\" href=\"Firefox.css\">");
}
else
{
document.write("<link type=\"text/css\" rel=\"stylesheet\" href=\"generic.css\">");
}
</script>
or
<!--[if IE]><link href="/ie.css" rel="stylesheet" type="text/css" /><![endif]-->

Related

IE8 issue - jQuery adjusting navigation html when page resizes

Using the below code, I don't want IE8 to pick up the responsive navigation. When a window is resized, IE8 is removing navigation. My has a class of "lt-ie9" for IE8. Can you tell me how to adjust the code so if the browser size is below 767, it will use the desktop version.
function resizeNav() {
if (!nav) {
nav = {};
nav.root = jQuery('#navigation');
nav.primary = nav.root.find('.menu');
nav.secondary = jQuery('.secondary-links');
nav.moveable = nav.secondary.children('li');
nav.icon = jQuery('<div id="menu-icon" class="btn">Navigation</div>');
nav.icon.click(function () {
nav.primary.slideToggle('slow');
nav.icon.toggleClass('active');
});
}
// Position everything
if (getWidth() <= 767) {
nav.moveable.appendTo(nav.primary);
nav.root.prepend(nav.icon);
nav.primary.hide();
} else {
nav.moveable.appendTo(nav.secondary);
nav.icon.detach();
nav.primary.show();
}
nav.icon.removeClass('active');
}
Assuming your lt-ie9 class is added the html element, the easiest way to do this is just check for it along with the width:
if (!html.lt-ie9 && getWidth() <= 767) {
You could also store the lt-ie9 as a boolean to be more efficient:
var isLtIe9 = $('html.lt-ie9').length;
And then modify the above to:
if (!isLtIe9 && getWidth() <= 767) {
Why use JS if you only want to effect IE8? Wouldn't it be better to just use an IE8 only CSS file. This would keep your code clean and hack free.
<!--[if lte IE 8]>
<link rel="stylesheet" type="text/css" href="ie8-and-down.css" />
<![endif]-->

internet explorer javascript style.height not working

I am trying to create a cookie policy alert for a website, just something simple like a bar at the top of the screen. The idea is that the user has to click close before the bar will disappear. The concept works fine in google chrome however in internet explorer 9, it does not alter its height when clicked.
Here is my code (I know it is basic but unfortunately it has to be due to the platform the establishment uses-
<script language=javascript type='text/javascript'>
function hideDiv() {
if (document.getElementById) { // DOM3 = IE5, NS6
document.getElementById('hideShow').style.height= '0px';
}
else {
if (document.layers) { // Netscape 4
document.hideShow.height= '0px';
}
else { // IE 4
document.all.hideShow.style.height= '0px';
}
}
}
function showDiv() {
if (document.getElementById) { // DOM3 = IE5, NS6
document.getElementById('hideShow').style.visibility = 'visible';
}
else {
if (document.layers) { // Netscape 4
document.hideShow.visibility = 'visible';
}
else { // IE 4
document.all.hideShow.style.visibility = 'visible';
}
}
}
</script>
<style>
#hideShow{
color:white;
font-family:Gill Sans MT;
text-align:center;
font-height:20px;
</style>
<div id="hideShow" ..etc>
My content
Close
</div>
Also, if anyone would be so kind, could you please explain how I could set it up so that the div 'hideShow' shows up until it is clicked, and then never again on that machine?
Please let me know if you need any more details.
Thanks in advance
Rob
The issue was that the height had to be defined within the hideShow css. As well as the font size. Then the javascript had to set height and fontSize to 0px.

Supporting Custom Elements in IE Compatibility mode

In Chrome and IE (non-compatibility), custom tags work fine as far as inspecting and navigating the DOM.
In IE+compatibility mode, it does not work.
Here is some sample code in jsbin: http://jsbin.com/ozajeh/1/edit
<html>
<!-- Run this in IE 8/9, possibly 10, with compatibility mode on to see the issue -->
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
if (document.createElement) {
document.createElement("myelement");
}
</script>
</head>
<body>
<script>
var div = $("<div>content</div>");
if( div.contents().length > 0 && div[0].childNodes.length > 0){
alert("found content in div");
}
var myElement = $("<myelement>content</myelement>");
if (myElement.contents().length > 0 && myElement[0].childNodes.length > 0) {
alert("found content in myelement");
}else{
alert("IE issue: cannot find content in myelement");
}
</script>
</body>
</html>
How can I get Internet Explorer in compatibility mode to deal with the tag correctly?
Current, what happens, is that myElement.nextSibling() returns the text node, which is obviously incorrect.
I can figure out a workaround based on property/value testing, but is there a more solid approach to handling this scenario?

Printing just an iFrame

I'm working on a case resolution system, and am currently using a jquery colorbox to display a list of open tasks to the user. Users want to be able to print this list, and I guess you can do it from within the page itself by adding a JavaScript link that triggers window.print from within the iframe. However, I've also got to account for users possibly selecting print from the browser's menu. In that case, if the colorbox is open, I just want to print its contents and not the overlying page.
Is it possible to hide everything except for the iframed content using a print media CSS file? If so, how can this be achieved? Failing that, I'll need to resort to JavaScript, so would achieving the effect in JavaScript be possible?
// suppose that this is how your iframe look like <iframe id='print-iframe' name='print-frame-name'></iframe>
// this is how you do it using jquery:
$("#print-iframe").get(0).contentWindow.print();
// and this is how you do it using native javascript:
document.getElementById("print-iframe").contentWindow.print();
In case the pure CSS solution will fail (didn't work for me but maybe I just missed something) you can have combined solution of CSS and JavaScript. First have this:
<style type="text/css" media="print">
.hideonprint { display:none; }
</style>
Then such JavaScript will cause all content to be hidden when printing, except your frame:
<script type="text/javascript">
window.onbeforeprint = function WindowPrint(evt) {
for (var i = 0; i < document.body.childNodes.length; i++) {
var curNode = document.body.childNodes[i];
if (typeof curNode.className != "undefined") {
var curClassName = curNode.className || "";
if (curClassName.indexOf("hideonprint") < 0) {
var newClassName = "";
if (curClassName.length > 0)
newClassName += curClassName + " ";
newClassName += "hideonprint";
curNode.setAttribute("original_class", curClassName);
curNode.className = newClassName;
}
}
}
document.getElementById("myframe").className = document.getElementById("myframe").getAttribute("original_class");
}
</script>
This also assume the iframe is direct child of the body otherwise it won't work either.
I have found a method that works to print just the IFrame's content even if the client uses the browser's print menu item, but I couldn't tell you why that is. The trick is to set the focus to the IFrame before printing. The print stylesheet is needed too, although the javascript seems to be what is happening when the user prints from the menu. You need both parts for it to work. It prints the entire document, even if it is larger than the IFrame! I have successfully tested it in IE8, Firefox 5 and 6 and Safari 3.2.
I use this script as a handler for an onclick event for a button or "print me" link:
<script type="text/javascript" language=JavaScript>
function CheckIsIE()
{
if (navigator.appName.toUpperCase() == 'MICROSOFT INTERNET EXPLORER')
{ return true; }
else
{ return false; }
}
function PrintThisPage()
{
if (CheckIsIE() == true)
{
document.content.focus();
document.content.print();
}
else
{
window.frames['content'].focus();
window.frames['content'].print();
}
}
</script>
The IFrame in question is named and id'd content. My button is in a div called print_iframe The browser sniffing is essential!
Then I use a print only stylesheet linked in like this:
<link href="/styles/print.css" rel="stylesheet" type="text/css" media="print" />
#charset "utf-8";
/* CSS Document */
body { background:none; }
#left { display:none; }
#main img { display:none; }
#banner
{
display:none;
margin-top:0px;
padding:0px;
}
#main
{
margin-top:0px;
padding:0px;
}
#print_iframe
{
display:none;
}
This could work if the iframe is a direct child of body
<style type="text/css" media="print">
body *{display:none}
iframe{display:block}
</style>

Detecting if a browser is in full screen mode

Is there any way of reliably detecting if a browser is running in full screen mode? I'm pretty sure there isn't any browser API I can query, but has anyone worked it out by inspecting and comparing certain height/width measurements exposed by the DOM? Even if it only works for certain browsers I'm interested in hearing about it.
Chrome 15, Firefox 10, and Safari 5.1 now provide APIs to programmatically trigger fullscreen mode. Fullscreen mode triggered this way provides events to detect fullscreen changes and CSS pseudo-classes for styling fullscreen elements.
See this hacks.mozilla.org blog post for details.
What about determining the distance between the viewport width and the resolution width and likewise for height. If it is a small amount of pixels (especially for height) it may be at fullscreen.
However, this will never be reliable.
Opera treats full screen as a different CSS media type. They call it Opera Show, and you can control it yourself easily:
#media projection {
/* these rules only apply in full screen mode */
}
Combined with Opera#USB, I've personally found it extremely handy.
You can check if document.fullscreenElement is not null to determine if fullscreen mode is on. You'll need to vendor prefix fullscreenElement accordingly. I would use something like this:
var fullscreenElement = document.fullscreenElement || document.mozFullScreenElement ||
document.webkitFullscreenElement || document.msFullscreenElement;
https://msdn.microsoft.com/en-us/library/dn312066(v=vs.85).aspx has a good example for this which I quote below:
document.addEventListener("fullscreenChange", function () {
if (fullscreenElement != null) {
console.info("Went full screen");
} else {
console.info("Exited full screen");
}
});
The Document read-only property returns the Element that is currently being presented in full-screen mode in this document, or null if full-screen mode is not currently in use.
if(document.fullscreenElement){
console.log("Fullscreen");
}else{
console.log("Not Fullscreen");
};
Supports in all major browsers.
Firefox 3+ provides a non-standard property on the window object that reports whether the browser is in full screen mode or not: window.fullScreen.
Just thought I'd add my thruppence to save anyone banging their heads. The first answer is excellent if you have complete control over the process, that is you initiate the fullscreen process in code. Useless should anyone do it thissen by hitting F11.
The glimmer of hope on the horizon come in the form of this W3C recommendation http://www.w3.org/TR/view-mode/ which will enable detection of windowed, floating (without chrome), maximized, minimized and fullscreen via media queries (which of course means window.matchMedia and associated).
I've seen signs that it's in the implementation process with -webkit and -moz prefixes but it doesn't appear to be in production yet.
So no, no solutions but hopefully I'll save someone doing a lot of running around before hitting the same wall.
PS *:-moz-full-screen does doo-dah as well, but nice to know about.
While searching high & low I have found only half-solutions.
So it's better to post here a modern, working approach to this issue:
var isAtMaxWidth = (screen.availWidth - window.innerWidth) === 0;
var isAtMaxHeight = (screen.availHeight - window.outerHeight <= 1);
if (!isAtMaxWidth || !isAtMaxHeight) {
alert("Browser NOT maximized!");
}
Tested and working properly in Chrome, Firefox, Edge and Opera* (*with Sidebar unpinned) as of 10.11.2019.
Testing environment (only desktop):
CHROME - Ver. 78.0.3904.97 (64-bit)
FIREFOX - Ver. 70.0.1 (64-bit)
EDGE - Ver. 44.18362.449.0 (64-bit)
OPERA - Ver. 64.0.3417.92 (64-bit)
OS - WIN10 build 18362.449 (64-bit)
Resources:
https://developer.mozilla.org/en-US/docs/Web/API/Screen/availWidth
https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth
https://developer.mozilla.org/en-US/docs/Web/API/Screen/availHeight
https://developer.mozilla.org/en-US/docs/Web/API/Window/outerHeight
In Chrome at least:
onkeydown can be used to detect the F11 key being pressed to enter fullscreen.
onkeyup can be used to detect the F11 key being pressed to exit fullscreen.
Use that in conjunction with checking for keyCode == 122
The tricky part would be to tell the keydown/keyup not to execute its code if the other one just did.
Right. Totally late on this one...
As of 25th Nov, 2014 (Time of writing), it is possible for elements to request fullscreen access, and subsequently control entering/exiting fullscreen mode.
MDN Explanation here: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Using_full_screen_mode
Straightforward explanation by David Walsh: http://davidwalsh.name/fullscreen
For Safari on iOS can use:
if (window.navigator.standalone) {
alert("Full Screen");
}
More:
https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
This works for all new browsers :
if (!window.screenTop && !window.screenY) {
alert('Browser is in fullscreen');
}
There is my NOT cross-browser variant:
<!DOCTYPE html>
<html>
<head>
<title>Fullscreen</title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
var fullscreen = $(window).height() + 1 >= screen.height;
$(window).on('resize', function() {
if (!fullscreen) {
setTimeout(function(heightStamp) {
if (!fullscreen && $(window).height() === heightStamp && heightStamp + 1 >= screen.height) {
fullscreen = true;
$('body').prepend( "<div>" + $( window ).height() + " | " + screen.height + " | fullscreen ON</div>" );
}
}, 500, $(window).height());
} else {
setTimeout(function(heightStamp) {
if (fullscreen && $(window).height() === heightStamp && heightStamp + 1 < screen.height) {
fullscreen = false;
$('body').prepend( "<div>" + $( window ).height() + " | " + screen.height + " | fullscreen OFF</div>" );
}
}, 500, $(window).height());
}
});
</script>
</body>
</html>
Tested on:
Kubuntu 13.10:
Firefox 27 (<!DOCTYPE html> is required, script correctly works with dual-monitors), Chrome 33, Rekonq - pass
Win 7:
Firefox 27, Chrome 33, Opera 12, Opera 20, IE 10 - pass
IE < 10 - fail
My solution is:
var fullscreenCount = 0;
var changeHandler = function() {
fullscreenCount ++;
if(fullscreenCount % 2 === 0)
{
console.log('fullscreen exit');
}
else
{
console.log('fullscreened');
}
}
document.addEventListener("fullscreenchange", changeHandler, false);
document.addEventListener("webkitfullscreenchange", changeHandler, false);
document.addEventListener("mozfullscreenchange", changeHandler, false);
document.addEventListener("MSFullscreenChanges", changeHandler, false);
This is the solution that I've come to...
I wrote it as an es6 module but the code should be pretty straightforward.
/**
* Created by sam on 9/9/16.
*/
import $ from "jquery"
function isFullScreenWebkit(){
return $("*:-webkit-full-screen").length > 0;
}
function isFullScreenMozilla(){
return $("*:-moz-full-screen").length > 0;
}
function isFullScreenMicrosoft(){
return $("*:-ms-fullscreen").length > 0;
}
function isFullScreen(){
// Fastist way
var result =
document.fullscreenElement ||
document.mozFullScreenElement ||
document.webkitFullscreenElement ||
document.msFullscreenElement;
if(result) return true;
// A fallback
try{
return isFullScreenMicrosoft();
}catch(ex){}
try{
return isFullScreenMozilla();
}catch(ex){}
try{
return isFullScreenWebkit();
}catch(ex){}
console.log("This browser is not supported, sorry!");
return false;
}
window.isFullScreen = isFullScreen;
export default isFullScreen;
2021, the Fullscreen API is available. It's a Living Standard and is supported by all browsers (except the usual suspects - IE11 and iOS Safari).
// toggle fullscreen
if (!document.fullscreenElement) {
// enter fullscreen
if (docElm.requestFullscreen) {
console.log('entering fullscreen')
docElm.requestFullscreen()
}
} else {
// exit fullscreen
if (document.exitFullscreen) {
console.log('exiting fullscreen')
document.exitFullscreen()
}
}
User window.innerHeight and screen.availHeight. Also the widths.
window.onresize = function(event) {
if (window.outerWidth === screen.availWidth && window.outerHeight === screen.availHeight) {
console.log("This is your MOMENT of fullscreen: " + Date());
}
To detect whether browser is in fullscreen mode:
document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement
according to caniuse you should be fine for majority of browsers.
This property returns the Element that is currently in fullscreen mode.
document.fullscreenElement; // HTML Element or null
Also, you can subscribe to fullscreen change events with this method
addEventListener('fullscreenchange', (event) => { });
You can combine both to detect the nature of the change
addEventListener('fullscreenchange', () => {
if (document.fullscreenElement) {
// Your Logic if fullscreen
}
});
More on this here.
You can detect full screen using CSS like this:
#media all and (display-mode: fullscreen) {
// Regular CSS to be applied in full-screen mode
}

Categories