This code only works based on the size of the browser at the time of loading, just wondering what could I implement for it get the current browser size and work based on that current information.
I have tried wrapping it in resize() but it causes it behave strangely, i.e the toggle goes on and off continuously , or when loading in a shrunk browser it doesnt work at all.
Its a responsive site where the footer menu is just static links on a large screen but turns into drop menu on small screen.
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
}
if(myWidth < 980) {
$("#footer h3").click(function () {
$(this).toggleClass("active");
$(this).parent().find("ul").slideToggle('medium');
});
}
var myWidth = 0, myHeight = 0;
function getSize(){
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
}
}
getSize(); // run first time
$(window).resize(function(){
getSize(); // do it on resize
});
$("#footer h3").click(function () {
getSize(); // not needed but good to have
if(myWidth < 980) {
$(this).toggleClass("active");
$(this).parent().find("ul").slideToggle('medium');
}
});
You should use css media queries instead:
#media only screen and (max-device-width: 980px) {
// css goes here...
}
OR include conditional style sheets:
<link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="small-device.css" />
Here is a great article disusing responsive design
Try something like this:
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) uniqueId = "Don't call this twice";
if (timers[uniqueId]) clearTimeout (timers[uniqueId]);
timers[uniqueId] = setTimeout(callback, ms);
};
})();
$(window).resize(function(){
waitForFinalEvent(function(){
// put all your code here
}, 20, "resize"); // replace 20 with every milliseconds to execute during
// resize
})
The code you put in there will execute every time the window resizes, simply using resize() won't always work because it doesn't necessarily check as you're resizing.
Related
Could somebody tell me why this gives an error?
I moved the code into functions to allow me to delay it so it's not so sensitive (was getting annoying)
Uncaught ReferenceError: hideleftnav is not defined
Uncaught ReferenceError: showleftnav is not defined
function showleftnav()
{
$(".leftnavdiv").css('width','500px');
$("body").css('padding-left','510px');
//get measurements of window
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
$('#maindiv').width(myWidth - 540);
}
function hideleftnav()
{
$(".leftnavdiv").width(10);
$("body").css('padding-left','20px');
//get measurements of window
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
$('#maindiv').width(myWidth - 50);
}
$(".leftnavdiv").live({ //code for autohide
mouseenter:
function () {
setTimeout("showleftnav()", 5000);
},
mouseleave:
function () {
setTimeout("hideleftnav()", 5000);
}
});
Looks like you've found one problem with using setTimeout with a string as the first argument. Here's a condensed example illustrating the same problem:
(function() {
function test() {
console.log('test');
}
setTimeout('test()', 500); // ReferenceError: test is not defined
setTimeout(test, 500); // "test"
setTimeout(function() { // "test"
test();
}), 500);
})();
Demo: http://jsfiddle.net/mXeMc/1/
Using the string causes your code to be evaluated with the window context. But since your code is in a callback function, test isn't accessible from window; it's private and restricted only to the scope of the anonymous function.
Referencing the function with just test avoids this problem because you're pointing directly to the function without using eval.
First of all, I'm not a javascript expert. I'm going crazy on trying to figure out how to make a conditional execution of a certain javascript. I'm using JQuery to absolutely center my block in a browser page, but only if the screen size is bigger than 480px (In other meaning, I don't want this script to run on smartphones). I'm using CSS media query to indicate my request. The thing is, this script works fine on all smartphones, Safari 5+, IE10, Firefox 13. BUT IT DOESN'T WORK ON IE6-9 and Opera 12 (As far as I understand, they don't support transitions). CAN ANYONE PLEASE HELP ME FIGURE OUT WHAT I AM DOING WRONG? And if there's a better way of doing this? (I tried #media query in CSS but The script keeps on running no matter what)... I would really appreciate the help.
<script>
if (matchMedia('only screen and (max-device-width:800px) and ' + '(orientation: portrait)').matches) {
// smartphone/iphone... maybe run some small-screen related dom scripting?
event.preventDefault();
} else{
//Absolute Content Center
function CenterItem(theItem){
var winWidth=$(window).width();
var winHeight=$(window).height();
var windowCenter=winWidth/2;
var itemCenter=$(theItem).width()/2;
var theCenter=windowCenter-itemCenter;
var windowMiddle=winHeight/2;
var itemMiddle=$(theItem).height()/2;
var theMiddle=windowMiddle-itemMiddle;
if(winWidth>$(theItem).width()){ //horizontal
$(theItem).css('left',theCenter);
} else {
$(theItem).css('left','0');
}
if(winHeight>$(theItem).height()){ //vertical
$(theItem).css('top',theMiddle);
} else {
$(theItem).css('top','0');
}
}
$(document).ready(function() {
CenterItem('.content');
});
$(window).resize(function() {
CenterItem('.content');
});
} //end of "else" (normal execution)
</script>
You can try this :-
<script>
var screenWidth = screen.width;
if (screenWidth > 480 ) {
//Absolute Content Center
function CenterItem(theItem){
var winWidth=$(window).width();
var winHeight=$(window).height();
var windowCenter=winWidth/2;
var itemCenter=$(theItem).width()/2;
var theCenter=windowCenter-itemCenter;
var windowMiddle=winHeight/2;
var itemMiddle=$(theItem).height()/2;
var theMiddle=windowMiddle-itemMiddle;
if(winWidth>$(theItem).width()){ //horizontal
$(theItem).css('left',theCenter);
} else {
$(theItem).css('left','0');
}
if(winHeight>$(theItem).height()){ //vertical
$(theItem).css('top',theMiddle);
} else {
$(theItem).css('top','0');
}
}
$(document).ready(function() {
CenterItem('.content');
});
$(window).resize(function() {
CenterItem('.content');
});
}
</script>
To get exact Height and Width in all browser is quite big deal because of IE, But no worries is the solution for all Browser including IE 6 to latest.
Here are those 2 function:
if (matchMedia('only screen and (max-device-width:800px) and ' + '(orientation: portrait)').matches) {
// smartphone/iphone... maybe run some small-screen related dom scripting?
event.preventDefault();
} else{
//Absolute Content Center
$(document).ready(function() {
CenterItem('.content');
});
$(window).resize(function() {
CenterItem('.content');
});
} //end of "else" (normal execution)
function CenterItem(theItem){
var winWidth=getWindowWidth();
var winHeight=getWindowHeight();
var windowCenter=winWidth/2;
var itemCenter=$(theItem).width()/2;
var theCenter=windowCenter-itemCenter;
var windowMiddle=winHeight/2;
var itemMiddle=$(theItem).height()/2;
var theMiddle=windowMiddle-itemMiddle;
if(winWidth>$(theItem).width()){ //horizontal
$(theItem).css('left',theCenter);
} else {
$(theItem).css('left','0');
}
if(winHeight>$(theItem).height()){ //vertical
$(theItem).css('top',theMiddle);
} else {
$(theItem).css('top','0');
}
}
function getWindowHeight() {
var myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
myHeight = document.body.clientHeight;
}
return myHeight;
}
function getWindowWidth() {
var myWidth = 0;
if( typeof( window.innerWidth ) == 'number' ) {
myWidth = window.innerWidth;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
myWidth = document.documentElement.clientWidth;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
myWidth = document.body.clientWidth;
}
return myWidth;
}
This will help you to get exact height in any Browser, in that way you can apply your logic. Hope this help!!!
Simplest thing is not to attach the event handler if the media query does not match.
$.fn.extend({
centerItem: function () {
return this.each(function () {
var $this = $(this),
hCenter = ( $(window).width() - $this.width() ) / 2,
vCenter = ( $(window).height() - $this.height() ) / 2;
$this.css({
left: hCenter > 0 ? hCenter : 0,
top: vCenter > 0 ? vCenter : 0
});
});
}
});
$(function() {
var bigScreen = 'only screen and (max-device-width:800px) and (orientation: portrait)';
if ( matchMedia(bigScreen).matches ) {
$(window).resize(function() {
$('.content').centerItem();
});
}
});
Notes
$() replaces $(document).ready(). See http://api.jquery.com/ready/
By convention, only object constructors start with a capital letter, so your CenterItem() function should actually be called centerItem().
I've turned your function into a jQuery plugin. You can of course continue using your own implementation if you find that confusing.
The .css() function can take an object argument so you can set multiple CSS properties in one step.
I've used the ternary operator (expression ? ifTrue : ifFalse) to replace the if.
You can do
window.innerHeight
window.innerWidth
to get the dimensions of the viewport. Now you could do:
var width = window.innerWidth
if (width > 480){
/* do desktop stuff*/
}
As alternative, you could go for the UserAgentString and/or Operating with:
window.navigator
(more reliable Detect-script)
However, either attempt might fail in some cirumstances.
edit: would be nice if you posted your match-media function.
edit2: use the script for correct viewport detection: https://stackoverflow.com/a/2035211/1047823
and then alter your code:
if ( getViewport()[0] < 480 ) {
// smartphone/iphone... maybe run some small-screen related dom scripting?
event.preventDefault();
} else{
// your desktop code
}
I doubt this is actually possible but Im prepared to be corrected.
What I need is to be able to detect the width and height of an iframe from within the iframe, so if the iframe src is iframeContent.html I need to be able to surface the values on this page.
I have no control over the page that hosts the iframe only the contents of the iframe.
Is this possible?
You can always get the web page dimensions, no matter if the page is loaded inside an iframe or a new window it always works the same way. This is a function I've found used to get window dimensions, you can also use it to get an <iframe> dimensions.
function alertSize() {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
window.alert( 'Width = ' + myWidth );
window.alert( 'Height = ' + myHeight );
}
source (thanks Andy E for adding the link)
jsFiddle example
Nowadays this is as simple as:
<script>
console.log(innerWidth, innerHeight)
</script>
Just make sure to load this JavaScript from within the iframe and it will print the iframe window's width and height in the browser's console.
http://dabbler.org/home/asdf/scrolling/test.html
Does anyone see anything wrong with this code?
I can't figure out what is wrong with it, but my intentions are such that when the user hits the bottom of the page, the page scrolls to the top.
Thanks.
You missed a closing parenthesis:
function getheight() {
var myWidth = 0,
myHeight = 0;
if (typeof (window.innerWidth) == 'number') {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
var scrolledtonum = window.pageYOffset + myHeight - 16;
var heightofbody = document.body.offsetHeight;
if (scrolledtonum = heightofbody) {
alert('asdf!')
}
//???? } <--
Here is a working version with some code fixes: http://jsfiddle.net/maniator/8zhmg/
On your last line you have
if (scrolledtonum = heightofbody)
That should be
if (scrolledtonum == heightofbody)
Not sure if that'll be the problem though
Your missing a closing tag on your function! (at the very end!)
Argh.. #Neal beat me to it!
I've been using the following code to detect browser client area width for ages and it wokred 100% with all browsers, including FF, Safari and various versions of IE. However, now when I switched to a new monitor with widescreen resolution (1280x800) this code fails on IE8. It reports clientwidth of 1024 !!!???
Any ideas how to get the correct client area width ?
function getClientWidth() {
var v=0,d=document,w=window;
if((!d.compatMode || d.compatMode == 'CSS1Compat') && !w.opera && d.documentElement && d.documentElement.clientWidth)
{v=d.documentElement.clientWidth;}
else if(d.body && d.body.clientWidth)
{v=d.body.clientWidth;}
else if(xDef(w.innerWidth,w.innerHeight,d.height)) {
v=w.innerWidth;
if(d.height>w.innerHeight) v-=16;
}
return v;
}
Non-jquery code I used some time ago:
function detectBrowserSize() {
var myWidth = 0, myHeight = 0;
if (typeof (window.innerWidth) == 'number') {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
alert(myWidth + ' - ' + myHeight)
}
The bits in your code where you check for window.opera and subtract 16 pixels are worrying. comp.lang.javascript's FAQ has a decent implementation of this.