How can I trigger jquery event at random time intervals? - javascript

I created a header using jquery.flip.js, found at https://github.com/nnattawat/flip. The plugin allows several ways to trigger the flip, the two relevant ones are 'click' and 'hover'. I was hoping to have the div's flip at random intervals automatically. I did find a similar question on stackoverflow that Heretic Monkey suggested using a recursive approach (Trigger mouse click and random intervals)...
var clickHand = function() {
$("[id^='hand_'].handIcon").trigger('click');
setTimeout(clickHand, (Math.random() * 3000) + 32000);
}
clickHand();
EDIT: sorry for not being clear. In the jquery code, the following method (?) handles the flip on click, however what I would like to do is have the divs flip automatically (if possible) without a hover or click to trigger. I tried using a setTimeout inside attachEvents, but it seemed to cause an issue with the styling.
attachEvents: function() {
var self = this;
if (self.setting.trigger === "click") {
self.element.on($.fn.tap ? "tap.flip" : "click.flip", $.proxy(self.clickHandler, self));
} else if (self.setting.trigger === "hover") {
self.element.on('mouseenter.flip', $.proxy(self.hoverHandler, self));
self.element.on('mouseleave.flip', $.proxy(self.unflip, self));
}
},
I am pretty new to javascript and am having a difficult time with this and any help would be appreciated.
I created a simple codepen, demonstrating the 3D flip, https://codepen.io/coeyflyer/pen/eYZGymG.
Thank you for any suggestions,
C

Related

capture setTimeout timerID when setTimeout is used in an if loop

I'm using setTimeout to create a pause in a loop (on mouseenter) and need to capture the timer ID so it can be stopped on mouseleave.
I thought that would be a simple task… before I tried to code it.
I have a gallery of thumbnails and on hovering over a thumbnail I want to cycle though a series of images (in an endless loop); kind of like a mini-carousel. I achieve this with the common method of swapping out the thumbnail’s source file path; I capture and store the thumbnail’s file path, loop through an array of images then replace the original thumbnail on mouseleave. Nothing complicated.
I coded this up and everything worked fine except on mouseenter the function looped through the entire array of images no matter how briefly the mouse hovered. I eventually discovered that you can’t actually pause a function or stop it but by wrapping it in a setTimeout and using a boolean flag you can create that effect. This is the answer I found https://stackoverflow.com/a/19192399 by user1693593, it’s really simple and works really well.
var doLoop = false;
function loopy() {
if (doLoop === true) {
setTimeout(function () {
// code to loop through array of images
loopy();
}, 11);
}
};
I'm using jQuery's hover method to set the flag.
$(".thumbnails").hover(function() {
doLoop = true;
}, function() {
doLoop = false;
});
So I coded that up and it worked perfectly when you hover over the first thumbnail but when you move to a new thumbnail it all goes haywire. I figured out this was because the first timeout wasn’t being cancelled and subsequent timeouts were interfering with it (and each other). I can see from various Stack Overflow questions that this is a common problem. I discovered that setTimeout returns an ID that you need to capture if you want to cancel it with clearTimeout.
So I found an example on MDN setInterval whereby you store the timeout ID in a variable. It looked simple enough so I coded that up and it worked perfectly. I can see in the console all the timeouts being set (with unique IDs) and cancelled as the mouse moves over the thumbnails… but now I can’t get the loop to work.
I can’t understand why this is so complicated in JavaScript, surely something like this is a common requirement.
Can someone please take pity on a relative newbie and explain how I can code user1693593's example so that it works when mousing over multiple elements. I don’t mind if it uses setTimeout or setInterval.
Please don’t mark this as a duplicate – I’ll understand if someone does – but I’ve been all over Stack Overflow (plus MDN and W3Schools) and I can’t find an example that specifically answers this question, certainly not one that I can understand anyway.
Store the reference somewhere and cancel it.
var timer = null
function addOne (elem) {
elem.textContent = (+elem.textContent + .1).toFixed(1)
}
$(".foo")
.on("mouseenter", function () {
var elem = this
timer = window.setInterval(function () { addOne(elem) }, 100)
}).on("mouseleave", function () {
if (timer) window.clearInterval(timer)
})
div.foo {
width:100px;
line-height: 100px;
border: 1px solid black;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foo">1</div>
<div class="foo">1</div>
<div class="foo">1</div>
<div class="foo">1</div>
<div class="foo">1</div>
Just keep track of the element that’s currently doing the loop instead of a boolean true/false.
var loopEl;
function loopy() {
if (loopEl) {
setTimeout(function () {
// code to loop through array of images
// do something with loopEl
loopy();
}, 11);
}
};
$(".thumbnails").hover(function() {
loopEl = this;
}, function() {
loopEl = false;
});

Why does jQuery.remove() remove mousedown listener from other div element?

I'm working on a HTML5 friendly drag and drop system and I've encountered another mystery that seems to make no sense...
The system is working in Edge - it's when I'm emulating IE8 that I encounter this latest problem.
I have a set of '.draggable' divs that get the following listener attached:
$(document).ready(function() {
$('#reset-button').click(resetDraggables);
if (!dragAndDropSupported()) {
var $draggables = $('.draggable');
$draggables.each( function (index) {
$(this).mousedown( jQueryStartDrag );
});
}
}
The draggables can be sent back to their original locations by hitting a 'reset' button. That all works fine.
The problem is - any divs that get sent back to their origins are no longer draggable. Even if I re-attach the listener in the reset function, it does not fire. Once again, this issue is only happening when I'm emulating IE8 and I don't remove the listener anywhere in my code.
function resetDraggables() {
if ( !$('#reset-button').hasClass('inactive') ) {
var $dropTargets = $('.drop-target');
$dropTargets.each(function (index) {
var draggableId = $(this).attr('data-contains');
var $originDraggable = $('#' + draggableId);
if ($originDraggable.attr('id')!=undefined) {
var $droppedDraggable = $(this).find('.draggable');
$droppedDraggable.remove();
$originDraggable.removeClass('inactive').addClass('draggable').attr('draggable', 'true').css('filter', 'alpha(opacity=100)').hide().fadeIn('fast');
$('#' + draggableId).mousedown( jQueryStartDrag );
$(this).removeClass('occupied').attr('data-contains', '');
$('#reset-button').addClass('inactive');
}
});
}
}
I've realised it's the $droppedDraggable.remove() line that's causing the problem. I'm not sure why a line to remove ONE object would remove the listener from another. The $droppedDraggable object was cloned from the other; Is that causing the issue?
Any ideas what might be going on?
OK, so I replaced the jQuery remove() lines with...
var droppedDraggable = document.getElementById('dropped-' + draggableId);
droppedDraggable.outerHTML = "";
...and that has done the trick. I'm guessing there must have been some hidden association made between the objects when one was cloned from the other and remove()ing one removed the mousedown listener from the other.
If anyone has a better theory, feel free to let me know, but this seems to have solved the problem.
Edit
I've just realised the above fixed the problem in IE8, but not in 9. Great! If anyone has any pointers on how NOT to include a bunch of browser-specific work arounds in my code, I'd be very keen to hear them. Thanks.

Limiting click detection on the page [javascript]

I'm trying to limit the user's ability to click on an object to a certain time limit. I looked around and found that apparently, setTimeout() is the correct function to use for this type of thing. I've applied the function to my code, but its not working. I'm thinking/know now that the problem is that the setTimeout in my code isn't limiting the actual click event, which I need to do. Here is a snippet of my click code:
function clickRun(event) {
var $objectVersion = correspondingObject(event.target.id);
if (isAnyVisible() == false) { // none open
$objectVersion.makeVisible();
} else if (isAnyVisible() && $objectVersion.isVisible()) { //click already open div
$objectVersion.makeInvisible();
} else if (isAnyVisible() && $objectVersion.isVisible()==false) { //different div open
searchAndDestroy();
$objectVersion.delay(600).makeVisible();
};
};
$('.ChartLink').click(function(event) {
setTimeout(clickRun(event),5000);
});
I've also created a JSFiddle to represent what I'm talking about: http://jsfiddle.net/FHC7s/
Is there a way to achieve limiting the actual click detection on the page?
I think the easiest way to do it is to keep track of the time of the previous click and if the current click is too soon after that, then don't do anything:
onClick = function(){
if(new Date().getTime() - lastCheck < MIN_CLICK_SPACING) return;
}
Have a look at this JSFiddle, I've set it up so you can have the button disable itself for time duration after detecting a click. Just make sure to remember how your closures are operating with your setTimeouts.
Your code contains an error... your line should be
setTimeout(function(){clickRun(event)},5000);
but even then I don't think that's exactly what you're looking for; that code will "delay" the click by 5 seconds, not actually prevent more clicks. If your true intent is to ignore all clicks after a certain amount of time, then I would go with mowwalker's answer; there's no way to stop the clicks, but you can check to see if you should honor them or not.

Trigger event on animation complete (no control over animation)

I've a scenario that requires me to detect animation stop of a periodically animated element and trigger a function. I've no control over the element's animation. The animation can be dynamic so I can't use clever setTimeout.
Long Story
The simplified form of the problem is that I'm using a third party jQuery sliding banners plugin that uses some obfuscated JavaScript to slide banners in and out. I'm in need of figuring out a hook on slideComplete sort of event, but all I have is an element id. Take this jsfiddle as an example and imagine that the javascript has been obfuscated. I need to trigger a function when the red box reaches the extremes and stops.
I'm aware of the :animated pseudo selector but I think it will need me to constantly poll the required element. I've gone through this, this, and this, but no avail. I've checked jquery promise but I couldn't figure out to use that in this scenario. This SO question is closest to my requirements but it has no answers.
P.S. Some more information that might be helpful:
The element isn't created by JavaScript, it is present on page load.
I've control over when to apply the plugin (that makes it periodically sliding banner) on the element
Most of the slideshow plugins I have used use changing classes at the end of the animation... You could extend the "addClass" method of jQuery to allow you to capture the class change as long as the plugin you use is using that method like it should:
(function($){
$.each(["addClass","removeClass"],function(i,methodname){
var oldmethod = $.fn[methodname];
$.fn[methodname] = function(){
oldmethod.apply( this, arguments );
this.trigger(methodname+"change");
return this;
}
});
})(jQuery);
I threw together a fiddle here
Even with obfuscated code you should be able to use this method to check how they are sending in the arguments to animate (I use the "options" object when I send arguments to animate usually) and wrap their callback function in an anonymous function that triggers an event...
like this fiddle
Here is the relevant block of script:
(function($){
$.each(["animate"],function(i,methodname){
var oldmethod = $.fn[methodname];
$.fn[methodname] = function(){
var args=arguments;
that=this;
var oldcall=args[2];
args[2]=function(){
oldcall();
console.log("slideFinish");
}
oldmethod.apply( this, args );
return this;
}
});
})(jQuery);
Well since you didn't give any indication as to what kind of animation is being done, I'm going to assume that its a horizontal/vertical translation, although I think this could be applied to other effects as well. Because I don't know how the animation is being accomplished, a setInterval evaluation would be the only way I can guess at how to do this.
var prevPos = 0;
var isAnimating = setInterval(function(){
if($(YOUROBJECT).css('top') == prevPos){
//logic here
}
else{
prevPos = $(YOUROBJECT).css('top');
}
},500);
That will evaluate the vertical position of the object every .5 seconds, and if the current vertical position is equal to the one taken .5 seconds ago, it will assume that animation has stopped and you can execute some code.
edit --
just noticed your jsfiddle had a horizontal translation, so the code for your jsfiddle is here http://jsfiddle.net/wZbNA/3/

Flickering mousenter mouseleave with delay, button list

I have made a list(<p>) with buttons. When I move my mouse over them it's a 1,2 sec delay before my textbox are marked with yellow to show where I can write. When I move my mouse away they turn normal(white).
My problem is when I quickly hover my mouse over the buttons back and forth a lot of the textboxes gets marked.
I had hoped the 1,2 sec delay would have worked then but it doesn't. But it works if I move my mouse slowly in and out of the button.
Here is a fiddle to it: http://jsfiddle.net/Pota/Fj6E6/
Here is my JavaScript code
$(function () {
$("p.pRespRoleId").mouseenter(function () {
var timeOut = 1200;
$this = $(this);
$this.data("delay", setTimeout(function () {
mouseInRespRoleId();
}, timeOut)
);
})
.mouseleave(function () {
$this = $(this);
if ($this.next(mouseOutRespRoleId()).is(":visible")) {
clearTimeout($this.data("delay"));
mouseOutRespRoleId();
}
else {
$this.next("p.pRespRoleId").show();
}
});
});
and
function mouseInRespRole()
{
var txtInRespRole = document.getElementById("<%=txtRespRoleName.ClientID %>");
txtInRespRole.style.background = "#FFFF00";
if (document.getElementById('txtRespRoleName').value == '')
{
document.getElementById('txtRespRoleName').innerHTML = txtInRespRole;
return false;
}
}
function mouseOutRespRole()
{
var txtOutRespRole = document.getElementById("<%=txtRespRoleName.ClientID %>");
txtOutRespRole.style.background = "white";
if (document.getElementById('txtRespRoleName').value == '')
{
document.getElementById('txtRespRoleName').innerHTML = txtOutRespRole;
return true;
}
}
Your jsFiddle is surely confusing to me (I am not sure what you are trying to achieve - there is a tangible possibility that you are overcomplicating things). I hope I got your requirement right...
Anyway, I believe your logic was right, but there were some flaws in the implementation. So, here is a modified (and partially corrected) version of your jsFiddle, which does what (I believe) you were trying to achieve.
Your use of '$this.next(mouseOutRespRoleId()).is(":visible")' was sure the most confusing, so I removed it completely. (In case it was fulfilling some other, not obvious purpose, you'll have to provide a more detailed description.)
The main problem was that $this.next(mouseOutRespRoleId()).is(":visible") was never evaluating to true, thus never clearing the timer that called mouseInRespRoleId().
EDIT:
I updated my jsFiddle illustration so that it takes care of IE9's strange behaviour (a.k.a. bug (?)). It should work without flickering now.
Short explanation of the problem:
Aparantly, in IE9 the mouse-events generation has some "timing issues", so that when entering (mouseOver) and leaving (mouseOut) a component multiple times rapidly, sometimes the mouse-events order gets messed up. E.g.:
The following event sequence (i.e. actual events):
mouseOver -> mouseOut -> mouseOver
May produce the following (obviously wrong) javascript-event sequence (i.e. events triggered by JS-engine in IE9):
mouseOver -> mouseOver(!) -> mouseOut(!)
So, I added an extra clearTimeout($this.data("delay")) in the "mouseentered" handler-function, in order to clear any pending scheduled executions of "mouseInRespRoleId".
It does not work perfectly on IE9 (and probably previous versions of IE - not tested), but it is as good as it can get (afaik).
(NOTE: It still works as intended on other (non-buggy) browsers.)

Categories