Reset jquery setTimeout after second Click on Button - javascript

I got a problem that wastes more and more time. Now I want to ask you guys to help me out. I really think it's not a big thing but I can't find the solution:
I have two code snippets, both really similar:
$(function () {
$('.plus--article').on('click', function () {
var $qty = $(this).closest('form').find('input[name="sQuantity"]');
var currentVal = parseInt($qty.val());
if (!isNaN(currentVal)) {
$qty.val(currentVal + 1);
$('.change-quantity--form').submit(function (e) {
var form = this;
e.preventDefault();
var timeout = setTimeout(function () {
$.overlay.open();
form.submit();
}, 2000);
});
}
});
$('.minus--article').on('click', function () {
var $qty = $(this).closest('form').find('input[name="sQuantity"]');
var currentVal = parseInt($qty.val());
if (!isNaN(currentVal) && currentVal > 0) {
$qty.val(currentVal - 1);
window.clearTimeout(timeout);
$('.change-quantity--form').submit(function (e) {
var form = this;
e.preventDefault();
setTimeout(function () {
$.overlay.open({
closeOnClick: false
});
form.submit();
}, 2000);
});
}
});
});
I just want to reset the timeout after a click on one of the buttons.

var time;
}, 2000); use this-> }, time);
$(".test").on("click", function(){
time = 0;
});

Related

Dynamically Create Load More Button

Trying to cobble together some code to create a "Load More" button for a JSON array i'm pulling down and dynamically populating the page with, using the jquery slice method. Still terrible at jquery would appreciate any assistance with this. Thanks so much.
Code:
function populateButtons(data) {
var rightcontent = $(".rightcontent");
var sub = document.createElement("a");
var gh_buttons = $(".rightcontent a")
sub.innerHTML = data.title;
sub.setAttribute("href", data.absolute_url);
sub.setAttribute("target", "blank");
sub.setAttribute("class", "hidden");
$(rightcontent).append(sub);
setTimeout(function() {
$(gh_buttons).slice(0,10).removeClass("hidden");
}, 100);
}
var populateButtons = gh_loadMore;
gh_loadMore = function() {
var loadMore = function() {
$(rightcontent).after("<button>Load More</button>");
};
$(loadMore).on('click', function (e) {
e.preventDefault();
$(gh_buttons).slice(10, 10).slideDown();
$('html,body').animate({
scrollTop: $(this).offset().top
}, 1500);
});
};
gh_loadMore();
There is an order problem for your code, you can implement like following.
function populateButtons(data) {
var sub = document.createElement("a");
sub.innerHTML = data.title;
sub.setAttribute("href", data.absolute_url);
sub.setAttribute("target", "blank");
sub.setAttribute("class", "hidden");
$(".rightcontent").append(sub);
var gh_buttons = $(".rightcontent a");
setTimeout(function() {
$(gh_buttons).slice(0,10).removeClass("hidden");
}, 100);
}
var gh_loadMore = function() {
$(".rightcontent").after("<button id='btn'>Load More</button>");
};
populateButtons(yourdata); // call it with yourdata variable
gh_loadMore();
$("#btn").on('click', function (e) {
e.preventDefault();
$(".rightcontent a").slice(10, 20).removeClass("hidden");
$(".rightcontent a").slice(10, 20).slideDown();
$('html,body').animate({
scrollTop: $(this).offset().top
}, 1500);
});

clearinterval() outside of jquery plugin

I create plugin something like this
timer plugin
(function($) {
$.fn.timer = function(options) {
var defaults = {
seconds: 60
};
var options = $.extend(defaults, options);
return this.each(function() {
var seconds = options.seconds;
var $this = $(this);
var timerIntval;
var Timer = {
setTimer : function() {
clearInterval(timerIntval);
if(seconds <= 0) {
alert("timeout");
}else {
timerIntval = setInterval(function(){
return Timer.getTimer();
}, 1000);
}
},
getTimer : function () {
if (seconds <= 0) {
$this.html("0");
} else {
seconds--;
$this.html(seconds);
}
}
}
Timer.setTimer();
});
};
})(jQuery);
and I call the plugin like this.
$(".myTimer").timer({
seconds : 100
});
i called the plugin at timerpage.php. When i changed the page to xxx.php by clicking another menu, the timer interval is still running and i need to the clear the timer interval.
i created a webpage using jquery ajax load. so my page was not refreshing when i change to another menu.
my question is, how to clear the timer interval or destroy the plugin when i click another menu?
Please try with following modifications:
timer plugin:
(function($) {
$.fn.timer = function(options) {
var defaults = {
seconds: 60
};
var options = $.extend(defaults, options);
return this.each(function() {
var seconds = options.seconds;
var $this = $(this);
var timerIntval;
var Timer = {
setTimer : function() {
clearInterval(timerIntval);
if(seconds <= 0) {
alert("timeout");
}else {
timerIntval = setInterval(function(){
return Timer.setTimer();
}, 1000);
$this.data("timerIntvalReference", timerIntval); //saving the timer reference for future use
}
},
getTimer : function () {
if (seconds <= 0) {
$this.html("0");
} else {
seconds--;
$this.html(seconds);
}
}
}
Timer.setTimer();
});
};
})(jQuery);
Now in some other JS code which is going to change the div content
var intervalRef = $(".myTimer").data("timerIntvalReference"); //grab the interval reference
clearInterval(intervalRef); //clear the old interval reference
//code to change the div content on menu change
For clearing timer associated with multiple DOM element, you may check below code:
//iterate ovel all timer element:
$("h3[class^=timer]").each(function(){
var intervalRef = $(this).data("timerIntvalReference"); //grab the interval reference
clearInterval(intervalRef);
});
Hope this will give an idea to deal with this situation.
Instead of var timerIntval; set the variable timerInterval on the window object, then you will have the access this variable until the next refresh.
window.timerIntval = setInterval(function() {
Then when the user clicks on any item menu you can clear it:
$('menu a').click(function() {
clearInterval(window.timerIntval);
});
Live example (with multiple intervals)
$('menu a').click(function(e) {
e.preventDefault();
console.log(window.intervals);
for (var i = 0; i < window.intervals.length; i++) {
clearInterval(window.intervals[i]);
}
});
(function($) {
$.fn.timer = function(options) {
var defaults = {
seconds: 60
};
var options = $.extend(defaults, options);
return this.each(function() {
if (!window.intervals) {
window.intervals = [];
}
var intervalId = -1;
var seconds = options.seconds;
var $this = $(this);
var Timer = {
setTimer : function() {
clearInterval(intervalId);
if(seconds <= 0) {
alert("timeout");
} else {
intervalId = setInterval(function(){
//Timer.getTimer();
return Timer.getTimer();
}, 1000);
window.intervals.push(intervalId);
}
},
getTimer : function () {
if (seconds <= 0) {
$this.html("0");
} else {
seconds--;
$this.html(seconds);
}
}
}
Timer.setTimer();
});
};
})(jQuery);
$(".myTimer").timer({
seconds : 100
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<menu>
Menu 1
</menu>
<div class="myTimer"></div>
<div class="myTimer"></div>
Just notice that it's little bit risky because you can only run it once otherwise the interval id of the second will override the first.

How to pause a .scrollTop() animation on mouseover? (jsfiddle included)

I am using the following jquery code to create a slow scrolling animation.
http://jsfiddle.net/fhj45f21/
Unfortunately I am having difficulties pausing the animation on mouse over. Could someone please have a look and give me a hint?
function Scroller(y){
this.times = 0;
this.moveInter = 0;
this.backInter = 0;
this.moveBack = function () {
var self = this;
clearInterval(this.moveInter);
this.backInter = setInterval(function () {
self.times -= 5;
y.scrollTop(self.times);
if (self.times == 0) {
return self.startMove();
}
}, 1);
}
this.move = function() {
var self = this;
this.moveInter = setInterval(function () {
self.times++;
y.scrollTop(self.times);
if (self.times == 1200) {
return self.moveBack();
}
}, 50);
}
this.startMove = function() {
this.times = 0;
var self = this;
if (this.backInter != null) {
clearInterval(this.backInter);
}
window.setTimeout(function () {
self.move();
}, 1000);
}
}
jQuery('.textBox').each(function () {
y = jQuery(this);
var scroller = new Scroller(y);
scroller.startMove();
});
Thanks a bunch!
Here you go: http://jsfiddle.net/nxk4vseq/
add an y.hover handler with functions for mousein and mouseout
var scrl=this;
y.hover(function(){
clearInterval(scrl.moveInter);
},function(){
scrl.move();
});

How to activate mouseleave, if it has been x amount of time?

So, I've got this type of situation, but I only want to "Do something" if the user "mouseleave(s)" for more than x amount of time, say one second. How should I implement that?
$("#someElement, #someOtherElement").mouseleave(function() {
// Do something.
});
Later I added:
$('.popover3-test').popover({
placement:'bottom',
template: $('.popover2'),
trigger: 'manual',
}).mouseenter(function(e) {
$(this).popover('show');
$(".popover3-test, .popover2").each(function() {
var t = null;
$(this)
.mouseleave(function() {
t = setTimeout(function() {
$('.popover2').hide();
}, 1000); // Or however many milliseconds
})
.mouseenter(function() {
if(t !== null)
clearTimeout(t);
})
;
});
});
setTimeout should do the trick:
$("#someElement, #someOtherElement").each(function() {
var t = null;
$(this)
.mouseleave(function() {
t = setTimeout(function() {
// Do something.
}, 1000); // Or however many milliseconds
})
.mouseenter(function() {
if(t !== null) {
clearTimeout(t);
t = null;
}
})
;
});
EDIT: If you want it to work on either, just remove the .each:
var t = null;
$("#someElement, #someOtherElement")
.mouseleave(function() {
t = setTimeout(function() {
// Do something.
}, 1000); // Or however many milliseconds
})
.mouseenter(function() {
if(t !== null) {
clearTimeout(t);
t = null;
}
})
;
$("#someElement, #someOtherElement").bind('mouseenter mouseleave', (function() {
var timer;
return function (e) {
if(e.type === 'mouseleave') {
timer = setTimeout(function () {
//do something
}, 1000);
} else {
clearTimeout(timer);
}
};
}()));
EDIT - usable on multiple elements
$("#someElement, #someOtherElement").bind('mouseenter mouseleave', function (e) {
var timer = $(this).data('timer');
if(e.type === 'mouseleave') {
timer = setTimeout(function () {
//do something
}, 1000);
} else {
clearTimeout(timer);
}
$(this).data('timer', timer);
};
});
this might not work as is, but gives you some ideas...
var elapsed = 0;
var timer = setInterval(function(){
elapsed += 20;
if( elapsed >= 1000 ) {
doSomething();
clearInterval(timer);
}
}, 20 );
$('#some').mouseleave(timer);
$('#some').mouseenter(function(){clearInterval(timer);elapsed=0;});

Rollover delay for Map markers

We had a developer work-up a piece of javascript for animating markers on a map for us. See http://luniablue.com/clients/endowment for it's current state.
The issue I'm having, is that the rollover is too sensitive and I want there to be a 1sec pause before executing the rollover function. From what I've read, I need to declare a setTimeout() function, but I'm not clear on where to insert that.
I have tried every place that I can see and I've had no luck except in breaking the script. I'm sure it's something stupid simple, but javascript isn't my stong point. Can anyone help me out?
Here's the code:
var firstEntry = true;
var lastOn = '';
function showAllPins() {
if ($('#communities').hasClass('theMouseIsOff')) {
var citiesArr = [];
$('.pin').each( function () {
citiesArr.push(this.id);
$('#'+this.id).hide();
});
var stillHidden = citiesArr.length;
while (stillHidden > 0) {
var a = Math.floor(Math.random()*citiesArr.length);
if ($('#'+citiesArr[a]).is(':hidden')) {
$('#'+citiesArr[a]).show().delay(Math.floor(Math.random()*900)).animate({
opacity: 1,
top: '+=40',
}, Math.floor(Math.random()*900), 'easeOutBounce');
stillHidden--;
}
}
firstEntry = true;
$('#communities').removeClass('theMouseIsOff');
}
}
function showPin(relid){
lastOn = relid;
if ($('#communities').hasClass('theMouseIsOff')) $('#communities').removeClass('theMouseIsOff');
if (firstEntry == true) {
$("#communities div[id!=" + relid + "].pin").animate({
opacity: 0,
top: '-=40',
}, 500);
firstEntry = false;
} else {
$("#communities div[id=" + relid + "].pin").animate({
opacity: 1,
top: '+=40',
}, 500, 'easeOutBounce');
}
}
function removeLastPin() {
$('#communities').addClass('theMouseIsOff');
$("#communities div[id=" + lastOn + "].pin").animate({
opacity: 0,
top: '-=40',
}, 500);
setTimeout('showAllPins()',600);
}
$(document).ready( function () {
$('.pin').mouseenter( function () {
relid = $(this).attr('rel');
showPin(relid);
}).mouseleave( function () { removeLastPin() });
});
$(document).ready(function() {
$('.pin').each(function() {
var selector = '#' + $(this).data('tooltip-id');
Tipped.create(this, $(selector)[0], { skin: 'light', hook: { target: 'topmiddle', tooltip: 'bottomleft'}});
});
});
Where you see:
$(document).ready( function () {
$('.pin').mouseenter( function () {
relid = $(this).attr('rel');
showPin(relid);
}).mouseleave( function () { removeLastPin() });
});
You can change it to:
$(document).ready( function () {
$('.pin').mouseenter( function () {
relid = $(this).attr('rel');
setTimeout(function(){showPin(relid)}, 1000);
}).mouseleave( function () { removeLastPin() });
});
By changing the showPin() function to execute after a timeout, the pin should appear after the specified interval.
Update:
If you would like the function only to run if the mouseleave hasn't occurred during the specified interval, you can clear the interval on mouseleave like this:
$(document).ready(function() {
$('.pin').mouseenter(function() {
relid = $(this).attr('rel');
var awaiting = setTimeout(function() {
showPin(relid)
}, 1000);
}).mouseleave(function() {
removeLastPin();
clearInterval(awaiting);
});
});

Categories