I want a website to execute a certain jquery script (which allows me to stretch the height of a vertical menu to the height of my browser window) when the page loads and when it is resized.
So I have written a jquery of this kind:
jQuery(document).ready(function ($) {
$(window).on('resize', function() {
<code to execute>
}).trigger('resize');
});
My problem is that this code works well when somebody loads the page or when he resizes it, but it doesn't work when one hits the refresh button. How could I make the code work also in that case?
Thank you in advance for your help.
Try this:
var myFn = function() { console.log('hello world') };
jQuery(document).ready(function ($) {
myFn();
$(window).on('resize', function() {
myFn();
});
});
jQuery(document).ready(function ($) {
function Resize(){
$(window).on('resize', function() {
<code to execute>
}).trigger('resize');
}
});
call this Resize() whenever you need. Either on load or on click.
It turned out that the way I described in my own question was more than right. It worked perfectly well that way, even onRefresh. What was not making my script work properly was the fact that one of the variables I was using would change after the page had finished loading, so when I was hitting "refresh", it would give a different value than in the beginning.
So for every user of stackoverflow.com, please note that whenever you want to set an event onLoad, onResize AND onRefresh, the easiest and best possible way is:
jQuery(document).ready(function ($) {
$(window).on('resize', function() {
<code to execute>
}).trigger('resize');
});
In fact, what glortho was suggesting could work, but that was using another variable, and in my humble opinion, that would make the whole thing a little more redundant.
Thank you everybody for your help and for reading.
Related
My website is : https://365arts.me/
So it loads about 16mbs of pics(Yes I know, I'm stupid. I'll try to change it very soon, also if someone could tell me a way to reduce size of do something else(like dynamic loading only when needed, if something like that exists) I'd be very grateful).
I added a preloader for it using:
[html]:
<div class="spinner-wrapper">
<div class="spinner">
<div class="dot1"></div>
<div class="dot2"></div>
</div>
</div>
and corresponging [jquery]:
<script>
$(document).ready(function() {
//Preloader
$(window).on("load", function() {
preloaderFadeOutTime = 500;
function hidePreloader() {
var preloader = $('.spinner-wrapper');
preloader.fadeOut(preloaderFadeOutTime);
}
hidePreloader();
});
});</script>
this works well but the problem is I have a javascript code that comes and says Hi! but it runs only for 2.8 seconds. So if loading takes up more than that, It doesnt show up. Can someone please tell me how to make sure that it loads only exactly after loading is completed.
Thanks a ton.
Code for my website:
https://github.com/richidubey/365-Days-Of-Art/blob/master/index.html
this may work
document.addEventListener('DOMContentLoaded', function() {
// your code here
}, false);
if you are happy with pure javascript
My first suggestion is to just get rid of the "Hi!" message since you already have a splash page in the form of the loader. But if you really want that second splash page, you can use the JQuery when() method:
$(window).on("load", function() {
$.when($('.spinner-wrapper').fadeOut(500)).then(displaySplashPage);
});
This assumes that displaySplashPage() is your function for showing the "Hi!" message.
You don't need $(document).ready() and window.on("load") here. Document ready waits for the HTML to be built, then applies event listeners/functions/etc to the structure. Window onload waits for everything to get loaded, then fires. In your case, you're trying to wait for all your pictures to load, so you only need onload.
You might need to have a container around all your main content set to opacity: 0 that switches to opacity: 1 as part of displaySplashPage(). That would prevent things from leaking through as you do the .fadeOut() on the loader.
JavaScript version - run js code when everything is loaded + rendered
window.onload = function() {
alert("page is loaded and rendered");
};
jQuery version (if you need it instead pure JS)
$(window).on('load', function() {
alert("page is loaded and rendered");
});
You can try this:
<script>
// Preloader
$(window).on("load", function() {
fadeOutTime = 500;
sayHelloDuration = 5000;
function hideSayHello() {
var sayHello = $('.say-hello');
sayHello.fadeOut(fadeOutTime);
}
function hidePreloader() {
var preloader = $('.spinner-wrapper');
preloader.fadeOut(fadeOutTime);
setTimeout(function() {
hideSayHello();
}, sayHelloDuration);
}
hidePreloader();
});
</script>
Also, remove the code from lines 83 ~ 87:
<script>
$(document).ready(function() {
$('.say-hello').delay(2800).fadeOut('slow');
});
</script>
About your website performance, you can improve a lot of things right now:
Use smaller thumbnail images on your front page, don't load FULL SIZE images at once. "work-showcase" section is really heavy without real necessity.
Try to incorporate src-set and smaller images for small screens, larger/heavier images for bigger screens. All modern browsers support it, and it will improve performance/loading speed.
Try to lazyload your big images, e.g. only when users scroll down to them, not before. It may take some work to integrate it with your image viewer, but it will additionally speed things up on initial load. My favorite library for this is this one: https://github.com/aFarkas/lazysizes but, you may find something else...
Unrelated to your original question, I have noticed that you have a bug in your HTML - see this screenshot. What kind of code editor do you use? Instead of empty space it apparently inserts invisible dots symbols which are not good. Actually, it's not the invisible dot (that's my editor's space indentation symbol), it's caused by 2 long dash (instead of short dash or minus) in your code after opening html comment tag:
I think the question is pretty much self explanatory...
I've got a script that is drawing some graphics across the window. Currently, if I resize the window (like taking it full screen) the script continues to affect only the windows' initial size. It should rerun, responding to the new dimensions.
I've tried adding this to my script.
$(window).resize(function() {
});
It did run whenever I resized it... but ONLY when I resized it! No more on load... as it also should.
I think I'm on the right path, but what am I missing?
Codepen here.
drawingFunction function(){
// your drawling code;
}
$(window).resize(function() {
console.log('window is resized');
drawingFunction();
});
$( document ).ready(function() {
drawingFunction(); // for onload
});
function drawStuff() {
// move here the drawing code ............
};
// call it where the loading process is
drawStuff();
// call it on resize , too
$(window).resize(function() {
drawStuff();
});
To call on loading
If you are using jQuery:
$(function(){
drawStuff();
})
if not, try this.
window.onload = function(){
drawStuff();
}
All is ok, but when I maximize or restore window, resize event is fired 2 times. When I press F11 in Firefox to go fullscreen, browser's toolbar is sliding up slowly and resize event is fired up to 40 times. My proposal is to use delay:
var timeout;
$(window).resize(function() {
clearTimeout(timeout);
timeout = setTimeout(onResizeOnly, 500);
});
function onResizeOnly()
{
//your code here
}
In the tag :
<body onresize="drawStuff()">
IMHO, it's the easiest way.
Ok, I have a Jquery script, its function is to determine the width of the window, onload. If the width is greater than 642px it calls .load() to load an image slider. The reason for this is mobile devices will neither be served the images or js required for the slider.
This worked fine when jquery was loaded in the head. Upon moving to the footer its breaking. The code is included from the index.php. Could this be whats causing it? I would have thought once php built the page jquery parsed the content?
It appears the code is parsed before the jquery is loaded. Can anyone suggest a way to get round this please?
I have thought of creating the code as pure JS or using a delayed load, but I cant seem to figure out how to get it working.
There must be much better solutions? I feel like I’m missing something very obvious..
contents of the included script:
<script type="text/javascript">
$(window).bind("load", function() {
// code here
$(window).width(); // returns width of browser viewport
var width = $(window).width();
if (width >= 642) {
$('.slider-content').load("templates/include/slider.php", function () {
$('.slider-content').show(200);
});
}
else {
//alert('small')
}
});
</script>
Thanks,
Adam
In some environments, you must use jQuery() instead of $(). See this question.
Other than that, your problem might have to do with the document not being complete yet or binding to an event that has already passed. Try this instead:
jQuery(document).ready( function($) {
// Your code goes here. (You can safely use the $() function inside here.)
});
I'm using a loading screen for a webpage and I use window.onload function.
Everything works great except in Mozilla Firefox browsers. When we first visit or refresh the page with ctrl+F5 combination, the loading screen never disappears. if we refresh the page only with F5, then it works.
I use the code below
$(window).load(function(e) {
$("#body-mask").fadeOut(1000,function(){
$(this).remove();
});
});
I have also tried the code below but nothing changed.
window.onload = function () {
$("#body-mask").fadeOut(1000,function(){
$(this).remove();
});
}
Why this is happening?
Please help.
Thanks in advance.
The problem is caused by another jquery background plugin which is placed inside $(document).ready()
I moved it inside $(window).load() function, now it works perfect.
I have also moved another function to resize images on the page load. When it was inside $(document).ready() block, sometimes it was malfunctioning if loading time took too long but now it also works great.
function resizeImages(){
//Some Code
}
$(window).load(function(){
$("#body-mask").fadeOut(1000,function(){
$(this).remove();
});
$.vegas({
src: backURL , fade:0
});
resizeImages();
});
$(document).ready(function(){
//Some Other code
});
I got the same problem when mistyped the type attribute in the script tag:
<script type="text/javascript">
Try This:
$(document).ready(function(e) {
$("#body-mask").fadeOut(1000,function(){
$(this).remove();
});
});
Read for load and ready functions difference What is the difference between $(window).load and $(document).ready?
You must call function on initialization like :
window.onload = init();
in other word modify your code to:
window.onload = function () {
$("#body-mask").fadeOut(1000,function(){
$(this).remove();
});
}();// Added
Copy following code in file then open it with firefox
<script>
window.onload = function () {
alert('saeed')
}();
</script>
This is probably basic to most reading, but I can't seem to figure it out.
I have a little test function that I want to execute if under a certain width. When the screen rotates or gets resized above that width, I want the function to cease to work. Here is some example code for simplicity sake.
enquire.register("screen and (max-width:500px)",{
match : function() {
$(".block .block-title").click(function(){
alert("Hello World!");
});
}
}).listen();
So if the page loads above 500px, it works as intended. Clicking won't execute. If the page loads at 500px or below, the click function executes. Only problem is that if you resize the viewport or change orientation to something above 500px, the function still executes. I'd like to be able to disable that.
The real world scenario I'm actually trying to do here is I have an un-ordered list of 4 items. Above a certain width they are displayed right away. If under a certain width, I just want to hide them and on click show them. I know there are a few ways to do it (.toggle(), .toggleClass("myclass"), etc).
I have done this a bunch of times but I always get caught with the entering / exiting break points and things not being reset, or working as intended. Usually it doesn't matter, but lately in some of my use cases it has mattered.
I know of the unmatch option but I'm not sure how to really kill the matched function above.
enquire.register("screen and (max-width:500px)",{
match : function() {
$(".block .block-title").click(function(){
alert("Hello World!");
});
},
{
unmatch : function() {
// what do I do here do kill above?
}
}
}).listen();
Any help would be appreciated. I am pretty sure it will help my current situation but will also help me expand my knowledge of enquire.js for other things.
Thanks.
edit: I forgot to mention... if you load the page under 500px, then resize or orientate wider then 500px, then go BACK under 500px, the click function won't work again.. which confuses me also. I basically was hoping it would work no matter what when under 500px, and not work at all when over 500px.
I'm the author of enquire.js, so hopefully I'll be able to help you ;-)
Basically, you want to add an event handler on match and remove event handler on unmatch. You seem to have the gist of how to do this above, but you've got the syntax a little wrong. Once the syntax is corrected it's just some jQuery knowledge to remove the click handler.
So let's look at how the syntax should be:
enquire.register("screen and (max-width:500px)", {
match: function() {
//match code here
},
unmatch: function() {
//unmatch code here
}
}).listen();
Notice that match and unmatch are part of a single object supplied to register.
Ideally you should be putting this in your document ready callback. To assign your click handler use jQuery's on method, as this allows you to use the off method to unassign:
$(".block .block-title").on("click", function() {
alert("hello");
});
$(".block .block-title").off("click");
This is great because you can even namespace your events, read up on the jQuery docs for more details on this. So to put it all together, we would have this:
$(document).ready(function() {
var $target = $(".block .block-title");
enquire.register("screen and (max-width:500px)", {
match: function() {
$target.on("click", function() {
alert("Hello World!");
});
},
unmatch: function() {
$target.off("click");
}
}).listen();
});
You can find a working example here: http://jsfiddle.net/WickyNilliams/EHKQj/
That should then be all you need :) Hope that helps!