Use variable from inside another function jQuery - javascript

I'm trying to use a variable from a function, but the variable does seem to work because I'm trying to use it outside the function.
The variable I'm trying to use is called 'viewportwidth', which I'm also trying to use after the first 'orientationchange resize' function.
Is there anyway to use this variable outside my function. I have attempted it below the first function in a new variable called 'sidebarwidth'
Please see code below. Can any one help?
$(window).bind("orientationchange resize", function(e) {
<?php if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'],'iPod')) echo "$('#wrapper, #sidebar').addClass('iphone-min-height');" ; ?>
var viewportwidth;
var viewportheight;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined')
{
viewportwidth = window.innerWidth,
viewportheight = window.innerHeight
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0)
{
viewportwidth = document.documentElement.clientWidth,
viewportheight = document.documentElement.clientHeight
}
// older versions of IE
else
{
viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
viewportheight = document.getElementsByTagName('body')[0].clientHeight
}
$( '#wrapper' ).css( {
'width' : viewportwidth + 'px',
'height' : viewportheight + 'px'
});
var iWebkit;
if(!iWebkit){
iWebkit=window.onload=function(){
function fullscreen(){
var a=document.getElementsByTagName("a");
for(var i=0;i<a.length;i++){
if(a[i].className.match("noeffect")){}
else{a[i].onclick=function(){
window.location=this.getAttribute("href");return false}}}}
function hideURLbar(){window.scrollTo(0,0.9)}iWebkit.init=function(){
fullscreen();
hideURLbar()
};
iWebkit.init()}}
}).trigger("resize");
var $openClose = $("span.open-menu"),
buttonwidth = $openClose.outerWidth(),
sidebarwidth = viewportwidth - buttonwidth,
$wrapper = $("#wrapper"),
$sidebar = $("#sidebar"),
menuOpen = false;
$sidebar.css({
'left' : '-210px',
'width' : sidebarwidth + 'px'
});
$openClose.on('click', function () {
if (menuOpen) { // run if button says "Close Menu"
$sidebar.stop().animate({ left: "-" + sidebarwidth + "px" }, 400);
$openClose.html("Menu");
$(this).addClass('active');
menuOpen = false;
} else { // run if button says "Open Menu"
$sidebar.stop().animate({ left: "0" }, 400);
$openClose.html("Close");
$(this).removeClass('active');
menuOpen = true;
}
});

Why are you doing this ?!
<?php
if( strstr($_SERVER['HTTP_USER_AGENT'],'iPhone')
|| strstr($_SERVER['HTTP_USER_AGENT'],'iPod'))
{
echo "$('#wrapper, #sidebar').addClass('iphone-min-height');" ;
}
?>
This is just stupid! Instead of doing this with using jQuery for it, you should be setting <body class="has-iphone">. There is no need for using bloatware.
This is pointless.
if (typeof window.innerWidth != 'undefined')
{
viewportwidth = window.innerWidth,
viewportheight = window.innerHeight
}
// IE6 in standards compliant mode (i.e. with a valid doctype as
//the first line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0)
{
viewportwidth = document.documentElement.clientWidth,
viewportheight = document.documentElement.clientHeight
}
// older versions of IE
else
{
viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
viewportheight = document.getElementsByTagName('body')[0].clientHeight
}
Nobody is supporting IE6 anymore , and which would be the "older IE" ? Do you really expect people with IE5.5 ?! This is just a bad case of copy-paste ...
As for the original problem, if you want to share variables between two or more function , and not put the in global scope, then use closures:
var handlers = (function () {
var shared_variable,
current;
return {
click: function (e) {
// code for click handler
},
mouseover: function (e) {
},
mouseout: function (e) {
}
};
}()),
menu = document.getElementById('menu');
$(document).on('click', handler.click);
$(menu).on('mouseover', handler.mouseover);
$(menu).on('mouseout', handler.mouseout);
All function will share the current variable, which, for example, is really useful when building a responsive menu.
P.S also, you should try to avoid setting css values in javascript. First of all it violates SoC and it also triggers Reflow in browser on each value you set.

Declare the variable outside the handler for orientationchange and resize. I also recommend wrapping everything in a closure to avoid polluting the global namespace:
(function(){
var viewportwidth;
var viewportheight;
$(window).bind("orientationchange resize", function(e) {
// Rest of your current code
})();

Move the variable out to a higher scope; it should then be available to both functions.
If they are global variables, both functions should be able to see them.

Take viewportwidth out of the resize function make it a global or attribute of some global object, then on resize set that variable, onclick calculate various values from viewportwidth and use them.

Related

Executing $(window).load() and $(window).resize() in Drupal 7

I'm trying to resize a couple divs on page load and window resize in drupal 7.
theme.info
name = Theme
description = The Theme
core = 7.x
stylesheets[all][] = css/style.css
scripts[] = js/scripts.js
(the rest)
scripts.js
$(window).load(function() {
getViewport();
});
$(window).resize(function() {
getViewport();
});
function getViewport() {
alert('function hit');
var viewportwidth;
var viewportheight;
if (typeof window.innerWidth != 'undefined')
{
viewportwidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
viewportheight = window.innerHeight || document.documentElement.clientHeight || document.body.clientWidth;
}
document.getElementById("content").style.height = (window.innerHeight - 150) + 'px';
document.getElementById('sidebar-first').style.height = (window.innerHeight - 50) + 'px';
}
But neither load, resize, or the function or getting hit. I'm sure it's my ignorance of utilizing this in drupal, but I can't seem to find the answer.
I've even tried including my own jquery library in the info file, but to no avail.
Thanks
No jQuery needed for this code to work, just create some event listeners and kill the $(window) method chains.
window.addEventListener('load', function() { getViewport() });
window.addEventListener('resize', function() { getViewport() });
Note:
You'll want to normalize addEventListener() if you need to target less than IE9. Something like:
if ( window.addEventListener ) {
// Modern browsers
window.addEventListener('load', function() { getViewport() });
window.addEventListener('resize', function() { getViewport() });
} else
// Browsers that need to die
window.attachEvent('onLoad', function() { getViewport() });
window.attachEvent('onResize', function() { getViewport() });
}

manipulate when inview.js is firing

i would like to know how i can manipulate the inview.js script that the moment when its fired is not at first pixels in viewport, and the last when the element is going out but rather for example 50pixels later or earlier.
the script of inview.js is
(function ($) {
function getViewportHeight() {
var height = window.innerHeight; // Safari, Opera
var mode = document.compatMode;
if ( (mode || !$.support.boxModel) ) { // IE, Gecko
height = (mode == 'CSS1Compat') ?
document.documentElement.clientHeight : // Standards
document.body.clientHeight; // Quirks
}
return height;
}
$(window).scroll(function () {
var vpH = getViewportHeight(),
scrolltop = (document.documentElement.scrollTop ?
document.documentElement.scrollTop :
document.body.scrollTop),
elems = [];
// naughty, but this is how it knows which elements to check for
$.each($.cache, function () {
if (this.events && this.events.inview) {
elems.push(this.handle.elem);
}
});
if (elems.length) {
$(elems).each(function () {
var $el = $(this),
top = $el.offset().top,
height = $el.height(),
inview = $el.data('inview') || false;
if (scrolltop > (top + height) || scrolltop + vpH < top) {
if (inview) {
$el.data('inview', false);
$el.trigger('inview', [ false ]);
}
} else if (scrolltop < (top + height)) {
if (!inview) {
$el.data('inview', true);
$el.trigger('inview', [ true ]);
}
}
});
}
});
// kick the event to pick up any elements already in view.
// note however, this only works if the plugin is included after the elements are bound to 'inview'
$(function () {
$(window).scroll();
});
})(jQuery);
all credits go to here
my attemp was to add a value to offset top top = $el.offset().top + 50, which works! but how can i change the value for the bottom up?
thanks ted
I'd recommend using http://imakewebthings.com/jquery-waypoints/
Which you can call like so to achieve your desired effect at 10% from the bottom:
$('.flyIn').waypoint(function() {
$(this).removeClass('hidden');
$(this).addClass('animated fadeInUp');
}, { offset: '90%' });

Dimensions of containerNode inside dojox dialog widget

I'm trying to get the dimensions of my containerNode which is a member of my dojox dialog widget, when the widget's showing animation ends.
this.dialog = new dojox.widget.Dialog( { sizeToViewport: true });
var dialogContainer = this.dialog.containerNode;
Which function or property should I use?
Since dojo V1.7 you could use dojo.position.
With the given example:
var position = dojo.position(dialogContainer);
var dimensions = {
width: position.w,
height: position.h
}
This call requires dojo/dom-geometry.
Let me know if it worked pls..
Ok, 2nd attempt now. As experimenting a little bit, didn't lead to a solution. How about a nasty little workaround?
Researching on the sizeToViewPort-option of the dojox.widget.dialog i found out, that by default there is a padding of 35px to the ViewPort. So if you know the size of the viewport, you could get the dimensions of the dialog by substracting the padding from it..
So maybe this helps:
function getNewDialog(the_padding) {
if (!the_padding || isNaN(the_padding)) {
the_padding = 35;
}
var dialog = new dojox.widget.Dialog({
sizeToViewport: true,
padding: the_padding + 'px' //nasty string conversion
});
return dialog;
}
function getViewPortSize() {
var viewPortWidth;
var viewPortHeight;
// mozilla/netscape/opera/IE7
if (typeof window.innerWidth != 'undefined') {
viewPortWidth = window.innerWidth;
viewPortHeight = window.innerHeight;
}
// IE6 in standards compliant mode
else if (typeof document.documentElement !== 'undefined' && typeof document.documentElement.clientWidth !== 'undefined' && document.documentElement.clientWidth !== 0) {
viewPortWidth = document.documentElement.clientWidth;
viewPortHeight = document.documentElement.clientHeight;
}
// older versions of IE fallback
else {
viewPortWidth = document.getElementsByTagName('body')[0].clientWidth;
viewPortHeight = document.getElementsByTagName('body')[0].clientHeight;
}
return {
width: viewPortWidth,
heigth: viewPortHeight
};
}
function getDialogSize(the_padding) {
if (!the_padding) {
the_padding = 35;
}
var vp_size = getViewPortSize();
return {
width: vp_size.width - the_padding,
heigth: vp_size.heigth - the_padding
};
}
var costumPadding = 35; // this is also the default value of dojox.widget.dialog ...
var dialog = getNewDialog(costumPadding);
var dialogSize = getDialogSize(costumPadding);
Hope I didn't miss anything.
This is one of possible sollutions
dojo.connect(mydialog, "show", function(){
setTimeout(function(){
var position = dojo.position(dialogContainer);
var dimensions = {
width: position.w,
height: position.h
}
alert(position.h);
},mydialog.duration + 1500);
});

Prevent Javascript from continuing a function if the screen is lower than 480 pixels

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
}

Find the exact height and width of the viewport in a cross-browser way (no Prototype/jQuery)

I'm trying to find the exact height and width of a browser's viewport, but I suspect that either Mozilla or IE is giving me the wrong number. Here's my method for height:
var viewportHeight = window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
I haven't started on width yet but I'm guessing it's going to be something similar.
Is there a more correct way of getting this information? Ideally, I'd like the solution to work with Safari/Chrome/other browsers as well.
You might try this:
function getViewport() {
var viewPortWidth;
var viewPortHeight;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined') {
viewPortWidth = window.innerWidth,
viewPortHeight = window.innerHeight
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0) {
viewPortWidth = document.documentElement.clientWidth,
viewPortHeight = document.documentElement.clientHeight
}
// older versions of IE
else {
viewPortWidth = document.getElementsByTagName('body')[0].clientWidth,
viewPortHeight = document.getElementsByTagName('body')[0].clientHeight
}
return [viewPortWidth, viewPortHeight];
}
( http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/ )
However, it is not even possible to get the viewport information in all browsers (e.g. IE6 in quirks mode). But the above script should do a good job :-)
You may use shorter version:
<script type="text/javascript">
<!--
function getViewportSize(){
var e = window;
var a = 'inner';
if (!('innerWidth' in window)){
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }
}
//-->
</script>
I've always just used document.documentElement.clientHeight/clientWidth. I don't think you need the OR conditions in this case.
Try this..
<script type="text/javascript">
function ViewPort()
{
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
var viewsize = w + "," + h;
alert("Your View Port Size is:" + viewsize);
}
</script>
Use this tipp: http://www.appelsiini.net/projects/viewport or that code: http://updatepanel.wordpress.com/2009/02/20/getting-the-page-and-viewport-dimensions-using-jquery/

Categories