Return updating variable from function - javascript

I'm trying to use javascript/jQuery to find the width of the window and use the variable in a later function.
$(function resizer() {
function doneResizing() {
var windowWidth = $(window).width();
return windowWidth;
}
var getWidth = doneResizing();
var id;
$(window).resize(function() {
clearTimeout(id);
id = setTimeout(doneResizing, 0);
});
doneResizing();
return getWidth;
});
var finalWidth = resizer()
So the resize function updates whenever the window is resized and windowWidth is updated automatically. When the variable is returned outside of the function, getWidth doesn't update with a window resize unless I refresh the page. Any ideas? I just picked up js/jq 2 weeks ago, and I'm doing my best to wrap my head around returns and closures, so I may have overlooked something here. Thanks.

it would be much simpler to do the following:
var finalWidth;
$( document ).ready(function() {
//Set this the first time
finalWidth = $(window).width();
$(window).resize(function() {
//resize just happened, pixels changed
finalWidth = $(window).width();
alert(finalWidth); //and whatever else you want to do
anotherFunction(finalWidth);
});
});
and use finalwidth outside as it is a global variable.
You get the same functionality without the complexity.
Update
As commented, global variables are bad practice ( e.g. also http://dev.opera.com/articles/view/javascript-best-practices/ ).
To avoid a global variable finalWidth can be moved inside document.ready and any necessary functions can be called from inside resize(function() { event handler.
Update 2
Due to the problem with dragging causing multiple resize events, code has been updated.
Reference: JQuery: How to call RESIZE event only once it's FINISHED resizing?
JSFiddle: http://jsfiddle.net/8ATyz/1/
$( document ).ready(function() {
var resizeTimeout;
$(window).resize(function() {
clearTimeout(resizeTimeout);
resizeTimeout= setTimeout(doneResizing, 500);
});
doneResizing(); //trigger resize handling code for initialization
});
function doneResizing()
{
//resize just happened, pixels changed
finalWidth = $(window).width();
alert(finalWidth); //and whatever else you want to do
anotherFunction(finalWidth);
}
function anotherFunction(finalWidth)
{
alert("This is anotherFunction:"+finalWidth);
}

You have mixed up your resizer function with the jQuery ready function.
To keep track on the window width you can do
(function ($) {
var windowWidth;
// when the document is fully loaded
$(function(){
// add an resize-event listener to the window
$(window).resize(function(){
// that updates the variable windowWidth
windowWidth = $(window).width();
})
// trigger a resize to initialize windowWidth
.trigger('resize');
// use windowWidth here.
// will be updated on window resize.
});
}(jQuery));

Related

jquery window load function not doing anything on load

posting for the first time on here, just wondering what im doing wrong within this little jquery script I wrote for a external html file containing my menu element. It works on resize just not load. I've tried a standalone $(window).load(); event as well and nothing seems to work. I'm new to jQuery and just know the do's and donts yet!
jQuery(document).ready(function($) {
var vwidth = $(window).width();
var vheight = $(window).height();
var menu = $('#menu_container');
$( window ).on('load resize', function() {
if (vwidth >= 1000) {
menu.css('zoom', '1');
} else {
menu.css('zoom', '0.8');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
There are two problems here. One already explained by #Mr. Polywhirl.
The other one is the fact that the DOM ready event will excute AFTER the window.load event. That means that by the time jQuery(document).ready executes $(window).load has already happened, so the event registration for window.load it's a bit late. Try this instead...
//this is essentially the same as jQuery(document).ready
$(function(){
toggleZoom();
$(window).on("resize", function(){
toggleZoom();
});
});
function toggleZoom(){
var vwidth = $(window).width();
//this isn't needed in this snippet
//var vheight = $(window).height();
var menu = $('#menu_container');
if (vwidth >= 1000) {
menu.css('zoom', '1');
} else {
menu.css('zoom', '0.8');
}
}
jQuery(document).ready(function($) {
Remove the dollar sign ($) from the function above. You are redefining the global as a function argument for the scope of the jQuery.ready function.
jQuery(document).ready(function() {
Edit
If that does not work, try some of these basic calls and see what the console prints out.
When I click the Run code snippet button, I get the following output:
Document ready()
Window resize()
Window load()
Window load() x2
Window resize()
$(document).ready(function() {
console.log("Document ready()");
});
$(window).on('load', function() {
console.log("Window load()");
});
// or
$(window).on({
load : function() {
console.log("Window load() x2");
},
resize : function() {
console.log("Window resize()");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The correct usage for jQuery ready() function is:
jQuery(document).ready(function(){
//The code you want to execute.
});
For more info look at:
https://api.jquery.com/ready/

Alert user if window.width is smaller then 950px jQuery

I'm trying to give an alert to the user once the window().width() is smaller then 950px. My JS looks like:
$(document).ready(function() {
function checkWidth() {
var windowSize = $(window).width();
if (windowSize < 950) {
alert("test");
console.log("screen width is less than 950px");
}
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);
});​
But nothing happens, not even my console.log().
Any suggestions? Thanks!
You have a UTF-8 BOM Character at the end of the code, that keeps it from working. Copy this code, which is exactly same as yours but free from the character. Make sure you are using a good editor like Sublime Text 2.
$(document).ready(function() {
function checkWidth() {
var windowSize = $(window).width();
if (windowSize < 950) {
alert("test");
console.log("screen width is less than 950px");
}
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);
});

Run jQuery script on window resize

I have a bit of script that will run various functions on a window resize,
$.event.add(window, 'load', resizeFrame);
$.event.add(window, 'resize', resizeFrame);
function resizeFrame(){
// various scripts //
}
This works absolutely fine, and the scripts I run in there work also. I then have a separate script that sets the height of various divs on document load, which also works just fine.
var h = 0,
target = $('.home #content .items-row .item article');
target.each(function(){
if (h < $(this).height()){
h = $(this).height();
}
});
target.each(function () {
$(this).css("height", h + 'px');
});
$('.testimonials .items-row').each(function () {
$('.span4 article', this).css('height',
Math.max.apply( Math,
$.map($('.span4 article', this), function(x) {
return $(x).height();
})
)
);
});
However when i try to combine the two, my divs will resize once on load, but not again on window resize. This is how i have combined the two,
function articleResize(){
var h = 0,
target = $('.home #content .items-row .item article');
target.each(function(){
if (h < $(this).height()){
h = $(this).height();
}
});
target.each(function () {
$(this).css("height", h + 'px');
});
$('.testimonials .items-row').each(function () {
$('.span4 article', this).css('height',
Math.max.apply( Math,
$.map($('.span4 article', this), function(x) {
return $(x).height();
})
)
);
});
}
$.event.add(window, 'load', resizeFrame);
$.event.add(window, 'resize', resizeFrame);
function resizeFrame(){
articleResize();
}
If anyone has any clues it would be greatly appreciated.
EDIT
as background here is the resizeFrame in its entirety,
function resizeFrame(){
var screenWidth = $(window).width();
function phoneEnable(){
$('#MainNav ul.nav').prependTo('.sidr-inner').addClass('nav-list nav-collapse');
$('#MainSocial ul.roundIcons').prependTo('.sidr-inner');
};
function phoneDisable(){
$('#sidr ul.nav').prependTo('#MainNav').removeClass('nav-list nav-collapse');
$('#sidr ul.roundIcons').prependTo('#MainSocial');
}
if (screenWidth >= 980){
phoneDisable();
} else{
phoneEnable();
};
var highestBox = 0;
$('.blog-featured .item article', this).each(function(){
if($(this).height() > highestBox)
highestBox = $(this).height();
});
$('.blog-featured .item article',this).height(highestBox);
articleResize();
};
Your load event was not firing in the samples I tried.
Instead of your current event registration try this:
JSFiddle: http://jsfiddle.net/j9SR5/1/
// jQuery DOM ready shortcut event handler (with locally scoped $)
jQuery(function($){
// Register for window resize
$(window).resize(resizeFrame);
// Do initial resize
resizeFrame();
});
Update: http://jsfiddle.net/TrueBlueAussie/j9SR5/5/
You are setting a fixed height, so the next time you resize the height is as specified previous (and will not change). The new JSFiddle resets the heights to their natural state first.
// Revert to height based on content
target.each(function () {
$(this).css("height", '');
});
jQuery is just wrapping the standard resize DOM event, eg.
window.onresize = function(event) {
...
};
jQuery may do some work to ensure that the resize event gets fired consistently in all browsers, but I'm not sure if any of the browsers differ,

Unload jquery function if window resize

I try to unload function if browser window less than 944px. I start to write this
$(window).resize(function() {
if ($(window).width() >= '944') {
$(window).load(function() {
$('#slider').nivoSlider();
});
} else {
alert($(window).width());
if ($(window).width() <= '944') {
$(window).unload(function() {
$('#slider').nivoSlider();
});
}
}
});
but i stuck. I want if the user enters, verify resolution and if more than 944px to load jquery function, however if browser is resize or less resolution than 944px, function will be unload.
i have a different solution for your problem; you can prepare a new slider mask (just like slider but without nivoSlider functions) for <944px window width, when browser width <944px niveSlider will be hide and your mask will be seen.
check it out:
$(window).resize(function() {
windowWidth = $(this).width();//you need to use this for changable values
if ( windowWidth > 943) {
$('#sliderMask').hide();
$('#slider').show();
$(window).load(function() {
$('#slider').nivoSlider();
});
} else if ( windowWidth < 944) {
$('#slider').hide();// hide your nivoSlider
$('#sliderMask').show();// show your basic slider mask
}
});
please note that: you need to use $(this) to get current value.
here is jsfiddle example for you; check the console log from your browser's developer panel

jQuery: Add or Remove function in a specific window size

I am very new to jQuery/JS and I have little problem with add or remove function in a specific window size.
I would appreciate if you can take a look at my code and correct it.
In detail, I use tinyscrollbar plugin that I want only appear in a specific window size(let's say above 650px of window width).
Here is my code:
<!--****preload latest jQuery and tinyscrollbar plugin, then...****-->
<script type="text/javascript">
function newsScroll() {
$("#newsScroll").tinyscrollbar();
};
/*
if windows width is less than 650px, remove newsScroll function and
switch DIV ID to "spNewsScroll" and vice versa.
*/
function scrollOnOff(width) {
width = parseInt(width);
if (width < 650) {
$(window).unbind(newsScroll);
$("#newsScroll").attr('id','spNewsScroll');
} else {
$(window).bind(newsScroll);
$("#spNewsScroll").attr('id','newsScroll');
}
};
$(function() {
//get window size as of now.
scrollOnOff($(this).width());
$(window).resize(function() {
scrollOnOff($(this).width());
});
});
</script>
Try this, tested and working :-)
Live demo: http://jsfiddle.net/oscarj24/fUsnj/21/
function scrollOnOff(width) {
width = parseInt(width);
if(width < 650){
$(window).trigger('newsScroll');
$('#newsScroll').attr('id','spNewsScroll');
} else {
$('.scrollbar').hide();
$('#spNewsScroll').attr('id','newsScroll');
}
};
$(function() {
$(window).bind('newsScroll', function(e) {
$('.scrollbar').show();
$('#newsScroll').tinyscrollbar();
});
var screenWidth = $(this).width();
scrollOnOff(screenWidth);
$(window).on("resize", function(event){
var w = $(this).width();
scrollOnOff(w);
});
});
​

Categories