I am trying to modify some existing code and can't get it working correctly. When the mouse is over div id "mine" I need the setinterval to stop and when the mouse is not over the div for the set interval to resume. I've tried and tried all day and night to get this working and just don't seem to be able to do it. Any help would be greatly appreciated. Thank you.
jQuery(document).ready(function(){
// check all
jQuery(this).on('click', '#selectall', function() {
jQuery('.checkbox').prop('checked', jQuery(this).is(":checked"));
});
// ajax
jQuery(this).on('submit', 'form[name="dispatchform"]', function(){
jQuery.ajax({
url: jQuery(this).attr('action'),
data: jQuery(this).serialize(),
type: 'post',
beforeSend: function(){jQuery('body').css('opacity', '0.5');},
success: function(data) {
var response = jQuery(data).find('#dispatchTable').html();
jQuery('#dispatchTable').html(response);
//message
var msg = jQuery(data).find('td.messageStackError, td.messageStackSuccess').html();
jQuery('#msg').css({
'padding': '10px',
'text-align': 'center',
'font-size': '12px',
'background-color': 'darkkhaki',
'margin': '10px 0',
'color': '#fff'
}).html(msg);
},
complete: function(){jQuery('body').css('opacity', '1');}
});
return false;
});
setInterval(function() {
jQuery.ajax({
url: jQuery(this).attr('action'),
data: jQuery(this).serialize(),
type: 'post',
beforeSend: function(){jQuery('body').css('opacity', '0.5');},
success: function(data) {
var response = jQuery(data).find('#dispatchTable').html();
jQuery('#dispatchTable').html(response);
//message
var msg = jQuery(data).find('td.messageStackError, td.messageStackSuccess').html();
if(msg !== undefined) {
jQuery('#msg').css({
'padding': '10px',
'text-align': 'center',
'font-size': '12px',
'background-color': 'darkkhaki',
'margin': '10px 0',
'color': '#fff'
}).html(msg);
}
},
complete: function(){jQuery('body').css('opacity', '1');}
});
}, 15000);
});
I'm not sure where, exactly you want that to happen...
What I mean is that I don't see div#mine anywhere in that code, so I don't know if it's supposed to be inside of one of those, or outside of all of them, or both outside, and also inside, if under special circumstances...
...regardless, the general idea is the following:
var doSomethingId;
function doSomething ( ) { }
var mine = document.querySelector("#mine");
mine.addEventListener("mouseover", function () {
doSomething();
doSomethingId = setInterval(doSomething, 10000);
});
mine.addEventListener("mouseout", function () {
clearInterval(doSomethingId);
});
There's not a whole lot more to it than that. The jQuery also isn't much smaller.
The key is to save the ID (var id = setInterval(/*...*/);) and use it to clear the interval (clearInterval(id);).
You don't "restart" the interval; rather, you call id = setInterval(...); again, so that the id is now the new interval, so you can stop the new interval.
Edit:
This is really an "XY" problem...
That is to say that you're looking for a solution to a problem that isn't really at the root of your problems, but rather a problem that is an offshoot, on top of the root.
A quick example:
most forms, I fill out by tabbing into, tabbing through the fields, and then either hitting ENTER, or tabbing down to the submit button and hitting ENTER
In this case (people who use keyboards/touchscreens/etc), you're still going to have the problem you're facing, now.
That said, if you're willing to refactor a little, the solution can be the same.
What I mean is, instead of your `setInterval(function () { jQuery./.../ });
What you want to do is something like;
var shouldUpdate = true,
form = this,
$mine = jQuery("#mine");
$mine.on("mouseover", function () { shouldUpdate = false; });
$mine.on("mouseout", function () { shouldUpdate = true; });
// whole setInterval(function () { jQuery.ajax(...); }); copied and pasted here, plus the `if`
function submitForm () {
if (!shouldUpdate) { return; }
jQuery.ajax(/* ... */);
}
var submitId = setInterval(submitForm, 15000);
// clearInterval(submitId); -- just remember to set the new ID, if you restart it
As you can see, I don't really need the interval to be started and stopped, now.
I've got an if that returns if I'm in any state that I shouldn't be updating in
(really, this should go one step further, and abort any XHR calls that are already happening, if you do start editing a field).
Based on this post I guess you'd like to accomplish something like this?
<!DOCTYPE html>
<html>
<head>
<style>
#mine{
width:200px;
height:200px;
border:1px solid red;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Counter:</p>
<div id="mine"></div>
<div id="counter">
</div>
<script>
jQuery(document).ready(function(){
$( "#mine" )
.mouseout(function() {
enableCounter();
})
.mouseover(function() {
disableCounter();
});
});
var count=10;
var counterEnabled = true;
var counter=setInterval(timer, 1000); //run every 1 second
function timer(){
if (counterEnabled)
count--;
if (count == 0){
alert('execute submit here!');
count = 10;
}
$('#counter').text(count);
}
function enableCounter(){
counterEnabled = true;
}
function disableCounter(){
counterEnabled = false;
}
</script>
</body>
</html>
Related
I've recieved function that should refresh chat box content and it should also scroll down to newest messages. I was using jQuery load(); for refresh, but it wasn't scrolling down, when I've recieved new message. Than, as I said, I've recieved ajax using function, which should replace my jQuery function. But it doesn't even load the content.
Both codes are below, I am so thankful for every advice, I feel really helpless now...
jQuery load():
$(document).ready(function(){
var out = document.getElementById("chat");
var auto = $('#chat');
var add = setInterval(function() {
// allow 1px inaccuracy by adding 1
var isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 1;
console.log(out.scrollHeight - out.clientHeight, out.scrollTop + 1);
// scroll to bottom if isScrolledToBotto
auto.load("chat_vypis.php")
if (isScrolledToBottom)
out.scrollTop = out.scrollHeight - out.clientHeight;
},500);
console.log(add);
return false;
});
Ajax using:
var needsToScrollToBottom=true;
var url='chat_vypis.php';
function updateChat() {
$.ajax({
url:url,
method:'GET',
success:function(data) {
var chat=$('#chat');
chat.html(data);
if (needsToScrollToBottom) {
scrollToBottom(chat);
}
},
//even on error, but after the call has completed
complete:function() {
setTimeout(updateChat,500);
}
});
}
function scrollToBottom(elem) {
elem.animate({ scrollTop: elem.height() }, "slow");
}
ok, after visiting your page, the main issue seems to be that the button submits the page instead of calling your function.
you need something like this:
$(document).ready(function() {
$('form').submit(function(e) {
// stop the submit
e.preventDefault();
// execute your function
updateChat();
});
});
i don't really know how to create time loop for this JS function..
Here is that function: enter link description here
Just what i need is a time loop every 20 seconds for a random sort..
I used - var ... = setInterval(..., 20000);
And - var ... = setTimeOut(...,20000);
But i don't know where to connect or if someone know better way how to do that everything gonna help me with that..
Thanks a lot for any help..
You have several issues with your attempt, the below will do what you want, just adjust the timer as needed
Updated CodePen
function loop() { // you had $(function loop(){... here, that is not right
$container = $('#Container');
if ($container.mixItUp('isLoaded')) { // check if the plugin has been initialized
$container.mixItUp('sort', 'random', true); // if loaded, just resort
// change true to false, to forego the animation
} else {
// if not initialized, do that now
$container.mixItUp({
load: {
sort: 'random'
},
layout: {
containerClass: 'list',
display: 'block'
}
});
}
}
$(function() { // here you had a for loop, not sure why but the int should have been var, anyway, I removed it altogether
setInterval(loop, 2000);
});
Try this:
http://codepen.io/anon/pen/BoZvEx
$(document).ready(function () {
var mixit = $('#Container').mixItUp({
load: {
sort: 'random'
},
layout: {
containerClass: 'list',
display: 'block'
}
});
function loop() {
mixit.mixItUp('sort', 'random');
};
var looper = setInterval(loop, 1000);
});
In there, the code is inside a $(document).ready, and there first we instantiate once, with the config in the parameter, and then the method loop does exactly just one call to sort.
$(document).ready(function(){
setTimeout(function(){
for( var i = 0; i < 10; ++i )
{
loop();
}
},20000);
});
I think you need this
I have the following piece of JQuery code which makes an ajax call every 20 seconds.
var uiBlocked = false;
var timerCount = 20;
window.setInterval(function() {
$.ajax({
cache: false,
type: 'HEAD',
url: '/heartbeat/',
timeout: 1000,
async: true,
success: function(data, textStatus, XMLHttpRequest) {
if (uiBlocked == true && navigator.onLine) {
uiBlocked = false;
$.unblockUI();
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if(textStatus != 'timeout'){
if (uiBlocked == false){
uiBlocked = true;
alert(textStatus);
$.blockUI({
message: 'Lost connectivity, please reconnect your VPN.<br/>Retrying in <span id="timer">20</span> .... secs.',
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'- moz-border-radius': '10px',
opacity: .5,
color: '#fff'
},
onBlock: function counterFunction() {
document.getElementById("timer").innerHTML= timerCount;
timerCount--;
if(timerCount >= 0){
setTimeout(counterFunction, 1000);
}
else{
timerCount = 20;
uiBlocked = false;
}
}
});
}
}
}
})
}, 20000);
Inside my error part I call the setTimeout function to decrement the counter. The counter decrements and alert is executed and counter resets to 20 seconds. But upon the second call the error callback does not get executed. This again gets executed on the third call.
Is my timer somewhere going wrong . Any help is appreciated.
This sounds like the quirky behavior of timers and intervals and the fact that JS is single threaded.
Its by no means a solution but i would recommend checking out this great post by John Resig - aka Mr jQuery.
How JavaScript Timers Work
I have the JS Ninja Book he authored and it has a similar chapter, was a real eye opener for me how these operators behave.
I think you may need setInterval instead of recursive setTimeout in your problem.
Here I made a jsFiddle to simplify your problem so that it's easier to understand:
$(function(){
var i = 20,
interval;
$('#button').click(function(){
i = 20;
if (interval){
clearInterval(interval)
}
interval = setInterval(function(){
if (i >= 0){
$('#counter').text(i--);
} else {
clearInterval(interval)
}
}, 1000);
});
});
As you can see, it is very important to reset the i variable (the timerCount in your example) as well as doing clearInterval() on previously declared setInterval()
Update:
In your case
var timer;
// ....
onBlock: function counterFunction() {
timerCount = 20;
if (iterval) {
clearInterval(interval);
}
interval = setInterval(function() {
if (timerCount >= 0) {
$('#timer').text(--timerCount);
} else {
clearInterval(interval);
uiBlocked = false;
}
}, 1000);
}
I use function App.loadTo to load some data in any place. I need a delay before displaying any content (used form-styler plugin, redrawing form). I tried setTimeout and setInterval functions, but they run just once, i.e.
1) Called App.loadTo( params ) - delay works
2) Called App.loadTo( params ) with the same params - delay doesnt work
I tried the following with no success
tmp = setInterval(function() {
console.log('I show all invisible!', params.where);
$(params.where).css({
'visibility': 'visible'
});
$('#preloader').remove();
clearInterval(tmp);
}, 110);
Where did I make a mistake?
App.loadTo = function loadTo(params) {
$.ajax({
url: '/' + params.controller + '/' + params.action + '',
type: 'POST',
dataType: 'json',
data: params.sentData,
success: function(server_answer, textStatus) {
if (server_answer.result == 'success') {
if (params.hasOwnProperty('parseHtml')) {
// Data parsing
var html = $(server_answer.html);
html = $(html).find(params.parseBlock);
} else {
var html = $(server_answer.html);
}
// Inserting data
$(params.where).empty().html(html).css({
'visibility': 'hidden'
}).before('<div id="preloader" style="width: 100%; background: url("i/preloader.gif") no-repeat scroll 50% center transparent; min-height: 140px; height: 100%;"></div>');
// Delay before display
setTimeout(function() {
console.log('I show all invisible!', params.where);
$(params.where).css({
'visibility': 'visible'
});
$('#preloader').remove();
}, 110);
} else {
alert_jq_ui(server_answer.error_txt);
}
},
error: function(xhr, errmsg, err) {
alert_jq_ui(xhr, errmsg, err);
}
});
};
Try clearing the setTimeout with clearTimeout(); if you choose to go with that, else if you rather want to try the setinterval method, try clearing it outside of itself, i hope this helps
I created a little fiddle, stripped down your code ... http://jsfiddle.net/gnsnvjtz/
The big difference here is this:
var App = {
loadTo: function () {
///loadTo code goes here ...
}
}
instead of `App.loadTo = function loadTo(params) ...
i have writen script which loads content from external php file. i'm using jquery1-9-1. my script works normal, except that moment when i'm clicking on button second time. there is delay for 0.5s before the animation starts. i think i know what is the problem and where is it. $("#header").animate({marginTop: "10px"... must execute just on the first click. after this clicked once, it must be deactivated. who knows how to solve it? don judge me so harsh and sorry my english
$(document).ready(function () {
var content = $("#content");
$("#main_menu a").click(function () {
var id = this.id;
$("#header").animate({
marginTop: "10px"
}, 500, function () {
$("#content").fadeOut(500, function () {
$("#content").load(id + ".php")
$("#content").fadeIn(500)
})
})
})
})
I have to ask, what is the point of caching content = $("#content") if you then refuse to use it and just call $("#content") repeatedly later?
Anyway, you need a variable to tell if it's the first run or not:
$(function () {
var content = $("#content"), isfirst = true;
$("#main_menu a").click(function () {
var id = this.id,
reveal = function() {
content.fadeOut(500, function () {
content.load(id + ".php")
content.fadeIn(500)
});
};
if( isfirst) $("#header").animate({marginTop: "10px"}, 500, reveal);
else reveal();
isfirst = false;
});
});
You need to track whether or not it has loaded, in that case. A simple variable and some closure should do it:
var isLoaded = false;
$("#main_menu a").click(function () {
var id = this.id;
if (!isLoaded) {
$("#header").animate({
marginTop: "10px"
}, 500);
isLoaded = true;
}
$("#content").fadeOut(500, function () {
$("#content").load(id + ".php")
$("#content").fadeIn(500)
})
});