How to return variable from jquery function - javascript

can you help me please...
How to return variable from jquery function
var height = $(window).height();
$(window).resize(function(){
var height = $(window).height();
return height;
});
setInterval(function() {
$('div').append( 'Index: ' + height );
}, 500);

You don't need to return. Try this:
var height = $(window).height(); // define "height" here
$(window).resize(function(){
height = $(window).height(); // update "height" variable,
// don't user "var" here.
// because using "var" will redefine
// "height" again and no longer contain the
// updated value on window resize
// out of this resize function scope
});
setInterval(function() {
$('div').append( 'Index: ' + height );
}, 500);

When you use var you're creating a new variable, not overwriting the original. You'll want this instead:
var height = $(window).height();
$(window).resize(function() {
height = $(window).height();
});
// ...

I suppose the answer to your question depends on how you want to return it. Console? Alert? A div or other element? See below for a list.
console.log(height)
alert(height)
$("#elementID").html(height); // or whatever selector and method work for your case
I suppose you could also convert that $(window).resize block into a function, then call that function. That should work, too.

Related

Add class after scroll on variable height div

Can someone spot the mistake in my JS syntax?
function setSize() {
var headerHeight = $('#header-blue:visible').height();
var subHeight = $('.subhead:visible').height();
var totalHeight = headerHeight + subHeight;
console.log(totalHeight);
}
// Set height variables on load
$(document).ready(function () {
setSize();
});
// Set height variables on window resize
$(window).resize(totalHeight);
// Fixed header on scroll
$(function() {
var header = $(".subhead");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= totalHeight) {
header.addClass(" fixed");
} else {
header.removeClass("fixed");
}
});
});
The goal here is to set a class when a scroll position is reached. The scroll position is variable because it depends on the height of 2 div's, which changes on mobile and desktop.
Unfortunately, I am receiving syntax errors saying totalHeight is not defined.
The variable totalHeight is only in the scope of the function setSize(), therefore it cannot be used outside the function. To solve the problem you have to make the variable global such as declaring it before the function:
var totalHeight;
function setSize()
You can also do the following:
var totalHeight = function(){
//code of the function here and make it return the value
}

Get, set and reset height using browser size and resize

I'm still an amateur when it comes to JS, I would like to get the height of the browser window, and then get it to update on resize. Is this possible? (code below)
$(document).ready(function() {
var winHeight = $(window).height(),
winWidth = $(window).width();
$('#wrap_project_horizontal_gallery').css({
'height' : winHeight - 170
});
});
I've thought about using setInterval but there must be a better way. Thanks very much for the help
EDIT: This needs to happen without a page refresh
You could bind a method to the resize event in the window and recalculate your variables there, or resize the elements that need resizing.
$(document).ready(function(){
$(window).resize(function() {
// your code here
});
});
or using a handler
$(document).ready(function(){
$(window).resize(handle_window_resize);
});
function handle_window_resize() {
// your code here
}
You can use the jQuery .resize() method.
$(window).resize(function() {
var winHeight = $(window).height(),
winWidth = $(window).width();
$('#wrap_project_horizontal_gallery').css({
'height' : winHeight - 170
});
});

Fluid sliding panel : make it work on load and after resize with computed values?

I'm trying to put together a fluid sliding panel which should take into account the inner width of the window on load, as well as on resizes : depending on the actual window size, the panel should be moved left / right a fourth of the window width.
So far i managed to bypass the multiple resize events happening when the user resizes the window, thx to this thread.
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = "Don't call this twice without a uniqueId";
}
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
var slidinNav = function(rtr){
document.getElementById('navPanel').style.left = -rtr + "px";
document.getElementById('navPanel').style.width = rtr + "px";
$('.showMenu').click(function(){
$('#navPanel').animate({left: '+=' + rtr +'px'}, 400);
});
$('.hideMenu').click(function(){
$('#navPanel').animate({left: '-=' + rtr + 'px'}, 400);
});
}
$(document).ready(function(){
var winW = window.innerWidth;
var navPosLeft=winW/4;
slidinNav(navPosLeft);
});
$(window).resize(function () {
waitForFinalEvent(function(){
var winW = window.innerWidth;
var navPosLeft=winW/4;
slidinNav(navPosLeft);
console.log(" Left / Width : " + navPosLeft);
}, 200, "un identifiant unique ?");
});
But being a complete javascript newbie i haven't found the solution to prevent the variables i use to store the window width value and offset to take all the successive values computed.
Better than a long and unclear explanation see jsfiddle here.
Here's my question : Should i reset variables (how and when) or rather try and get the last value (and again : how and when) ?
Thx for any help on this one ; - )
Correct me if I am not understanding exactly what you are looking for here but it looks to me like you may be making it more complicated than it needs to be.
Looks like you could simply just stay with using % and just have these functions:
$('.showMenu').click(function(){
$('#navPanel').animate({left: 0}, 400);
});
$('.hideMenu').click(function(){
$('#navPanel').animate({left: "-20%"}, 400);
});
As demonstrated here: http://jsfiddle.net/X9Jrc/3/

Get browser width and height after user resizes the window

Is there any way to get the browser width and height after a user has resized the window. For example if the window is 1920 by 1080 and the user changes the window to 500 by 500 is there any way to get those two new values in JavaScript or jquery?
Pure Javascript answer:
var onresize = function() {
//your code here
//this is just an example
width = document.body.clientWidth;
height = document.body.clientHeight;
}
window.addEventListener("resize", onresize);
This works fine on chrome. However, it works only on chrome. A slightly more cross-browser example is using the event target properties "outerWidth" and "outerHeight", since in this case the event "target" is the window itself. The code would be like this
var onresize = function(e) {
//note i need to pass the event as an argument to the function
width = e.target.outerWidth;
height = e.target.outerHeight;
}
window.addEventListener("resize", onresize);
This works fine in firefox and chrome
Hope it helps :)
Edit: Tested in ie9 and this worked too :)
If you need to know these values to do layout adjustments, I bet you plan on listening to those values. I recommended using the Window.matchmedia() API for that purpose instead.
It is much more performant and is basically the JS equivalent of CSS media queries.
Very quick example of use:
if (window.matchMedia("(max-width: 500px)").matches) {
/* the viewport is less than or exactly 500 pixels wide */
} else {
/* the viewport is more than 500 pixels wide */
}
You can also setup a listener that'll get called every time the state of the matches property changes.
See MDN for description and example of using a listener.
It's possible by listening to resize event.
$(window).resize(function() {
var width = $(window).width();
var height = $(window).height();
})
You can use the JQuery resize() function. Also make sure you add the same resize logic to reload event. If user reloads in the sized window your logic won't work.
$(window).resize(function() {
$windowWidth = $(window).width();
$windowHeight = $(window).height();
});
$(document).ready(function() {
//same logic that you use in the resize...
});
Practically, I use this and it helps me a lot:
var TO = false;
var resizeEvent = 'onorientationchange' in window ? 'orientationchange' : 'resize';
$(window).bind(resizeEvent, function() {
TO && clearTimeout(TO);
TO = setTimeout(resizeBody, 200);
});
function resizeBody(){
var height = window.innerHeight || $(window).height();
var width = window.innerWidth || $(window).width();
alert(height);
alert(width);
}
You can use the resize event, along with the height() and width() properties
$(window).resize(function(){
var height = $(window).height();
var width = $(window).width();
});
See some more examples here
Use jQuery resize method to listen window size change . inside callback you can get height and width.
$(window).resize(function(){
var width = $(window).width();
var height = $(window).height();
});
Simplest way to get real width and height of an element after window resize as the follow:
<div id="myContainer">
<!--Some Tages ... -->
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function () {
$(window).resize(function () {
//The below two lines of codes more Important to clear the previous settings to get the current measure of width and height
$('#myContainer').css('height', 'unset');
$('#myContainer').css('width', 'unset');
var element = $('#myContainer');
var height = element.height();
var width = element.width();
//Below two lines will includes padding but not border
var innerHeight = element.innerHeight();
var innerWidth = element.innerWidth();
//Below two lines will includes padding, border but no margin
var outerHeight = element.outerHeight();
var outerWidth = element.outerWidth();
//Below two lines will includes padding, border and margin
var outerHeight = element.outerHeight(true);
var outerWidth = element.outerWidth(true);
});
});
</script>
You can use the event object to get the height and width, I use destructuring assignment and the target points to window:
const handleGetDim = ({ target }) => ({
width: target.innerWidth,
height: target.innerHeight,
});
window.addEventListener('resize', handleGetDim);

Use JQuery to resize container based on window size

I am trying to have a container div resize based on the dimensions of the window. The height to width ratio is the most important aspect here and I want to maximize the size of the container in whichever direction (height or width) that is most constraining given the ratio. I have tried a few things unsuccessfully with this being the most recent:
$(window).load(function() {
var h = $(window).height();
var w = $(window).width();
If((h/w)>0.61){
$('#container').css({'height': h, 'width':h*1.64}); }
else{ $('#container').css({'height': w/1.64, 'width':w}); }
})
What do I need to change to get the window to resize? Is there a better way to approach this?
Thanks in advance for any assistance. I am not at all familiar with javascript/JQuery and have been unable to find any useful info... this thing is driving me nuts...
You want to capture the resize event, so assuming your current code works to your likings
$(document).ready(function() {
$(window).resize(function() {
var h = $(window).height();
var w = $(window).width();
if((h/w)>0.61) {
$('#container').css({'height': h, 'width':h*1.64});
}
else {
$('#container').css({'height': w/1.64, 'width':w});
}
});
});
And let's avoid the capital I on the if
I typically use this:
function resize () {
var w = $(window);
var containerWrap = $('#container-wrap');
containerWrap.css({ width:w.width(), height:w.height()});
}
I'm not sure if that answers your ratio question.
EDIT:
This may be more helpful:
$(document).ready(function () {
var missionWrap = $('#mission-wrap');
var w = $(window);
w.on('load resize',function() {
missionWrap.css({ width:w.width(), height:w.height()});
});
});

Categories