I have a jQuery function :
$(document).ready(function() {
setInterval(function() {
$.post("../user/getdashboard/", function(data) {
$("#users_available").html(data);
});
}, 3000);
}
I have to convert it into window.onload function.
How to do it?
If you want it vanilla js, use onload callback of the window object:
window.onload = function() {
setInterval(function() {
$.post("../user/getdashboard/", function(data) {
$("#users_available" ).html(data);
});
}, 3000);
}
But you could even use load event with jQuery, what is basically the same:
$(window).on('load', function() {
setInterval(function() {
$.post("../user/getdashboard/", function(data) {
$("#users_available").html(data);
});
}, 3000);
});
But keep in mind, that a jQuery ready state is not the same as window.onload. These are two different things. So this might have unexpected impacts to your project/page.
You can handle the readystatechange event,
document.onreadystatechange = function () {
if (document.readyState === "interactive") {
// Your code
}
}
window.onload waits for everything, including images, which probably is overkill.
Related
I am trying to exceute a javascript function after another div that has been popupated by javascript has loaded. The div has been populated first with javascript is '#am-events-booking'. The function i am trying to use is:
$(window).load(function ()
{
var i = setInterval(function ()
{
if ($('#am-events-booking').length)
{
clearInterval(i);
}
}, 1000);
alert('Page is loaded');
});
I always use $(document).ready() to run code after the page has loaded. Not sure what the difference is, but at least then it works.
Furthermore you need to use .text() to get the text inside an element.
Working code snippet:
$(document).ready(function() {
var i = setInterval(function() {
if ($('#am-events-booking').text().length) {
clearInterval(i);
console.log('Text detected!');
} else {
console.log('Waiting...');
}
}, 1000);
console.log('Page is loaded');
});
setTimeout(loadText, 2200);
function loadText() {
$('#am-events-booking').html("<h2>Hello</h2>");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="am-events-booking"></div>
$(document).ready(findDiv);
function findDiv() {
if($('#am-events-booking').is(':visible')){ // if the div is visible
alert('Page is loaded');
} else {
console.log("loading...");
setTimeout(findDiv, 50); // wait 50ms,
}
}
$('body').html('<div id="am-events-booking"></div>');
<body></body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
you can use is :visible form JQuery to check if div is added or not
Sorry for the basic level of the question, but js definitely isn't my area of expertise. However, it's one of those questions that's difficult to Google an answer on.
I basically want to do a couple of things when the window is resized. I have a little bit of extra code that also stops the resize event firing twice.
The issue is that I'm duplicating bits of code, that as a coder, I know is wrong. The problem is I don't know how to go about making it right. Here's my current duplicated code:
Event binding
$(window).on("resize", resizeText);
$(window).on("resize", resizeIndicator);
Functions
function resizeIndicator() {
clearTimeout(id);
id = setTimeout(updateIndicator, 200);
}
function resizeText() {
clearTimeout(id);
id = setTimeout(updateText, 200);
}
Thse are not duplicated but included for completeness:
function updateIndicator() {
$tab = $(".tabs li.focus");
if ($tab.length) {
toggleIndicator($tab, true);
}
}
function updateText() {
$tabs = $(".tabs li:not(.indicator) a");
$tabs.each(function () {
$(this).toggleClass("two-line", this.scrollWidth > $(this).outerWidth());
});
}
So you want to avoid code duplication? No problem use higher order of function to create new function.
function createResizeCallback(resizeFunc) {
var id;
return function () {
clearTimeout(id);
id = setTimeout(resizeFunc, 200);
}
}
$(window).on("resize", createResizeCallback(updateText));
$(window).on("resize", createResizeCallback(updateIndicator));
function updateIndicator() {
console.log('updateIndicator');
}
function updateText() {
console.log('updateText');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Declare your timeout id globally and use single handler.
Working demo: http://jsbin.com/nugutujoli/1/edit?js,console,output
$(window).on("resize", resizeEvent);
var timeout;
function resizeEvent() {
clearTimeout(timeout);
timeout = setTimeout(function(){
updateIndicator();
updateText();
}, 200);
}
function updateIndicator() {
console.log("update indicator fired.");
}
function updateText() {
console.log("update text fired.");
}
This is my current code to run the series of setTimeout functions. How do I stop these when either the mouse moves, or is over a certain element?
$( document ).ready(function() {
clicky()
function clicky() {
setTimeout(function () {jQuery('#1500').trigger('click');}, 3000);
setTimeout(function () {jQuery('#1990').trigger('click');}, 6000);
setTimeout(function () {jQuery('#2010').trigger('click');}, 9000);
setTimeout(function () {jQuery('#battle').trigger('click');}, 12000);
setTimeout(function () {
jQuery('#water').trigger('click');clicky()
}, 15000);
}
});
You essentially need to save a reference to your timeouts so that they can be cleared when you need them to be. In the following example, I just used an object so that you could specify which timeout you wanted to affect, if desired.
Here's a working fiddle that will clear the timeouts on hover, then reset them when the mouse leaves: http://jsfiddle.net/6tQ4M/2/
And the code:
$(function(){
var timeouts = {};
function setTimeouts () {
timeouts['#1500'] = specifyTimeout('#1500', 3000);
timeouts['#1990'] = specifyTimeout('#1990', 6000);
timeouts['#2010'] = specifyTimeout('#2010', 9000);
timeouts['#battle'] = specifyTimeout('#battle', 12000);
timeouts['#water'] = specifyTimeout('#water', 15000, function(){
console.log('reset the timeouts');
clearTimeouts();
setTimeouts();
});
}
function clearTimeouts () {
for(var key in timeouts){
if(timeouts.hasOwnProperty(key)){
clearTimeout(timeouts[key]);
delete timeouts[key];
}
}
}
function specifyTimeout (id, time, callback) {
return setTimeout(function(){
$(id).trigger('click');
if(callback){
callback();
}
}, time);
}
$('a').on('click', function(){
$('#projects').append('clicky clicky!');
});
$('#map').on('mouseover', clearTimeouts);
$('#map').on('mouseleave', setTimeouts);
setTimeouts();
});
Let me know if you have any questions about the code at all!
Your setTimeout needs to be defined to a variable, so that it can be cleared by passing to clearTimeout(). Something like:
var interval = setTimeout(function() {
//msc
}, 8000);
window.clearTimeout(interval);
Well, according to what you ordered, when you hover an area, the setTimeOut should be fired, and when you are out of this region, the setTimeOut should be reset.
This is the code:
HTML
<div id="map"></div>
CSS
#map{
width:100px;
height:100px;
background-color: black;
}
Javascript
var timeoutHandle;
$('#map').mouseover(function(event){
window.clearTimeout(timeoutHandle);
});
$('#map').mouseout(function(event){
timeoutHandle = window.setTimeout(function(){ alert("Hello alert!"); }, 2000);
});
Basically you should keep a reference to the setTimeOut, in this case the variable is timeoutHandle, call clearTimeOut on mouse over and call setTimeOut again to reset the timer.
Here is the jsFiddle:
http://jsfiddle.net/bernardo_pacheco/RBnpp/4/
The same principle can be used for more than one setTimeOut timer.
You can see more technical details here:
Resetting a setTimeout
Hope it helps.
I want to reload window after a this custom function finishes:
<script type="text/javascript">
$(document).ready(function(){
setTimeout(function () {
$('#order_form').dolPopupHide({});
}, 3000);
//window.location.reload();
});
</script>
Is there a way I can add the reload to the setTimeout function so it doesn't run until the timeout is over?
reload needs to be inside your function:
$(document).ready(function(){
setTimeout(function () {
$('#order_form').dolPopupHide({});
window.location.reload();
}, 3000);
});
If you want to conceptually separate the work from the reload, you can do something like this:
$(document).ready(function(){
setTimeout(function () {
doWork();
window.location.reload();
}, 3000);
function doWork() {
$('#order_form').dolPopupHide({});
}
});
Or, to be even more general:
function reloadAfterExec(fn)
return function() {
fn();
window.location.reload();
}
}
$(document).ready(function(){
setTimeout( reloadAfterExec(function() {
$('#order_form').dolPopupHide({});
}), 3000);
});
i have a jquery function that when clicked produces a set timeout on making a div visible.
however, if another option is selected during the settimeout length, i would like to know how to destroy this function and stoop anything else in it happening.
my current code is:
$(document).ready(function () {
$('li#contact').click(function () {
$('ul.image_display').css('display', 'none');
$('ul.projects').fadeOut().hide();
$('li#cv').removeClass('cur');
$('li#projects').removeClass('cur');
$('li#contact').addClass('cur');
$('ul.contact').fadeIn(function () {
setTimeout(function () {
$('ul.contact').fadeOut('slow');
}, 8000);
});
setTimeout(function () {
$('li#contact').removeClass('cur');
$('li#cv').addClass('cur');
$('ul.projects').fadeIn('slow');
$('ul.image_display').css('display', 'block');
}, 8625);
});
});
a bit cumbersome but works until this is clicked:
$(document).ready(function () {
$('#projects').click(function () {
$('li#cv').removeClass('cur');
$('ul.contact').fadeOut().hide();
$('#contact').removeClass('cur');
$('ul.projects').fadeIn('slow');
$('#projects').addClass('cur');
$('ul.image_display').css('display', 'block');
});
});
if the second is clicked just after the first than class 'cur' still comes up on li#cv after the set time.
The setTimeout function returns an identifier to that timeout. You can then cancel that timeout with the clearTimeout function. So you can do something like this (fill in the blanks with your code):
var timer;
$(function() {
$(...).click(function() {
...
timer = setTimeout(...);
...
});
$(...).click(function() {
clearTimeout(timer);
});
});
It's not particularly super clean to keep a global variable for this, however. You could store the timer in the data attribute of whatever element makes the most sense for your situation. Something like this:
$(function() {
$(...).click(function() {
...
var timer = setTimeout(...);
$(someelement).data('activetimer', timer);
...
});
$(...).click(function() {
var timer = $(someelement).data('activetimer');
if(timer) {
clearTimeout(timer);
$(someelement).removeData('activetimer');
}
});
});
It doesn't really look cleaner, but it's an alternative way to store the timer...
You can use clearTimeout() to do that. You'll need to keep the return value from setTimeout() in a variable to pass to clearTimeout().