jquery window load function not doing anything on load - javascript

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/

Related

When and how to call a javascript function which looks for page scrolling action?

I have written a code to look for page scrolling. It works when I put it inside script tag.
How to put this code inside a function and let it look for page scrolls?
Here is my code
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
alert('scrolling');
}
});
I did not understand exactly what you ask,something like this ? (put this in a script tag or an external js file)
$(document).ready(function() {
$(window).scroll(function(e){
detect_scrollPage(e);
});
});
function detect_scrollPage(event){
...
}
What about this:
function scrollBinder(selector, callback){
$(selector).scroll(function(e){
callback.call(this, e);
});
}
$(document).ready(function() {
scrollBinder('#some_div', function(div, event) {
//do calcl here
})
//or on window
scrollBinder(window, function(div, event) {
//do calcl here
})
});
Any way it is a shorthand, most people will do that the same as you did.

Check browser width after resize, without reload (Javascript)

I have a small piece of Javascript that checks what the browser's width is on load and, depending on the result, runs a piece of jQuery. This to display a different menu on mobile devices
However, it CAN happen a user starts with a very small browser on his desktop, running the jQuery (and therefore the mobile menu). If he then resizes to full-screen, the menu doesn't change, because the check on the browser's width doesn't run again.
The question: How do I adapt the Javascript so it checks every time the browser is resized?
My code:
if (window.innerWidth <= 992) {
jQuery(document).ready(function($) {
$(".main-menu").hide();
$(".mobile-nav-button").click(function() {
$(".main-menu").slideToggle(500);
});
});
}
else {
jQuery(document).ready(function($) {
$(".mobile-nav-button").hide();
$(".mobile-cart-button").hide();
});
}
You can use a resize function wrapper like this:
function resize(){
// do all your stuff here
}
And then call it once on page load, and recall it on every resize event:
$(document).ready(function(){
resize();
$(window).resize(resize);
});
Instead of the wrapper you could also use an anonymous function ($(window).resize(function(){/*Do stuff here*/})), but then you can't call your function on page load and you'd have to repeat yourself.
Your specific case
In your specific case you'd have to take out the document readys. Heres how it should look:
function resize(){
// First we need to show all, then we will selectively hide based on page width
$(".main-menu, .mobile-nav-button, .mobile-cart-button").show();
if (window.innerWidth <= 992) {
$(".main-menu").hide();
// also, because you bind a click event here, you'll need to unbind it every time
// otherwise it will be executed multiple times after a couple of resizes
// (you could also do what #david does and move this into the document.ready below)
$(".mobile-nav-button").off("click").click(function() {
// slideToggle will toggle display of an element, but because its wrapped in click()
// it only gets executed onclick, not resize. Also, you don't want animation on resize.
$(".main-menu").slideToggle(500);
});
} else {
$(".mobile-nav-button").hide();
$(".mobile-cart-button").hide();
}
}
$(document).ready(function(){
resize();
$(window).resize(resize);
});
A snippet
Below is a snippet with the code working. I reduced the width to 700 pixels so I could see the effects at a smaller screen difference (because that how the snippet editor looks) but it all works.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="mobile-nav-button">Mobile Nav Button</div>
<div class="mobile-cart-button">Mobile CART Button</div>
<div class="main-menu">MAIN MENU</dov>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function resize(){
$(".mobile-nav-button, .mobile-cart-button, .main-menu").show();
if (window.innerWidth <= 700) {
$(".main-menu").hide();
$(".mobile-nav-button").off("click").click(function() {
$(".main-menu").slideToggle(500);
});
} else {
$(".mobile-nav-button").hide();
$(".mobile-cart-button").hide();
}
}
$(document).ready(function(){
resize();
$(window).resize(resize);
});
</script>
</body>
</html>
you can use
jQuery(document).ready(function($) {
$(".mobile-nav-button").click(function() {
$(".main-menu").slideToggle(500);
});
$(window).resize(function()
{
if (window.innerWidth <= 992) {
$(".main-menu").hide();
}
else {
$(".mobile-nav-button").hide();
$(".mobile-cart-button").hide();
}
));
$(window).resize();
));
Just call resize function on pageLoad
$(document).ready(function($) {
$(window).resize(YourFunctionName);
$(window).resize();
});
function YourFunctionName() {
// Here is your code which you want to run automatically on page resize.
}

JavaScript failing on page postback

I have got this script to give effects to buttons which i have, it fails after the page is posted back, i have also put the code in a pageLoad method yet it still does not function. any idea how i can go about making this script run once the page has loaded.
$(document).ready(function () {
/*preloader for image loading bar*/
jQuery(function ($) {
function preLoad() {
//alert("script running");
$("#divQuestionMatrix").addClass("hidden");
}
function loaded() {
$("#divQuestionMatrix").removeClass("hidden");
$('div#preLoader').css({ display: 'none' }).remove();
}
preLoad();
window.onload = loaded;
});
/* End of preloader*/
$("#btnPrevious").click(function (e) {
$("#navigation").val("previous");
}
);
$("#btnNext").click(function (e) {
$("#navigation").val("next");
}
);
/* $(".qmatrix").click(function () {
//get id of button
alert($(this).attr('id'));
$("#navigation").val($(this).attr('id'));
}
);*/
$(".qmatrix").hover(function (e) {
//get id of button
//alert($(this).attr('id'));
//get src of image before hover
var origimage = $(this).attr('src');
// alert(origimage);
//$(this).attr({ src: 'images/questionMatrix/100' + $(this).attr('id') + '.png' });
$(this).stop().animate({ "opacity": "0.1" }, "fast")
},
function () {
// $(this).attr({ src: '' + origimage.toString() + '' });
$(this).stop().animate({ "opacity": "1" }, "fast");
}
);
The document.ready event is fired once the page has finished loading.
Inside the handler for the ready event, you're then using the ready event shortcut (passing a function directly to the global jQuery function (which is the same as the global $ function btw) to add another handler function for the ready event.
Inside this second ready handler you're then trying to assign the loaded function to window.onload, which would have already fired by this point.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Put this Latest Jquery Library Just just above to your document.ready() function and try to run your program.

Scrolling not working in javascript

I have a scroll function
$('#lisr').scroll( function() {
if($(this).scrollTop() + $(this).innerHeight()>= $(this)[0].scrollHeight)
{
//DO some code
}
}
The problem is when I scroll down and it hits the bottom it executes the code twice instead of once, so If I make any ajax call in it, it is made twice, what I am missing in it?
The scroll() function binds to the scroll event - which is fired many times when the user scrolls the page.
Write your code with the assumption that it can be called more than once:
var completed = false;
function doSomeCode() {}
function isAtBottomOfPage() {}
$('#lisr').scroll(function () {
if (!completed && isAtBottomOfPage()) {
doSomeCode();
completed = true;
}
});
jsfiddle: http://jsfiddle.net/kZJ9k/1/
As a more advanced note, you probably shouldn't bind your logic directly to the scroll event; you run the risk of causing lag for your users when scrolling. Read more about this from John Resig:
http://ejohn.org/blog/learning-from-twitter/
Here are my codes for endless scrolling. What I do is unbinding the scroll event until the ajax request finishes. You can also use a variable as a flag and check/change its value before calling ajax request. Hope it helps:
$(document).ready(function(){
$(window).bind('scroll', loadPage);
});
var loadPage = function(){
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$(window).unbind('scroll');
$.ajax({
//Your things here
success: function(result){
// Do success here
$(window).bind('scroll', loadPage);
},
error : function(xhr){ //Do error here }
});
}
}
$('#lisr').scroll( function() {
if($(this).scrollTop() + $(this).innerHeight() > $(this)[0].scrollHeight)
{
//DO some code
}
}

Return updating variable from function

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));

Categories