I have the following JS code
$('body').on({
click: function()
{
var el = $(this);
lookUpTask(el);
el.bind('blur', function(){
timeOutTask = setInterval(function(){
if( timeOutTask )
{
clearInterval(timeOutTask);
el.trigger('remove_match');
}
}, 500);
$('body').on({
click: function(event)
{
var match = $(this);
var color = match.attr('color');
// Check color to change brightness
var brightness = hexToLuminance(color);
var text_color = '#000';
if( brightness < 128 ) {
text_color = '#fff';
}
// Change color according to brightness
el.css('color',text_color);
el.parent().parent().children('.remove').css('color',text_color);
el.parent().parent().children('.resize').css('color',text_color);
// Change the background and task name
el.parent().parent().css('background-color', color);
el.val(match.html());
// Update DB
// Remove the task_match
el.trigger('remove_match');
}
},'.match');
});
el.bind('remove_match', function(){
if( el.val == "" ) {
el.val('Select Task');
}
el.css('text-align','center');
el.parent().children('.match_results').remove();
clearInterval(timeOutTask);
});
},
keyup: function(event)
{
lookUpTask($(this));
}
},'.task_select');
What I am trying to do is when the user clicks on .task_select, then I bring up the matched results and display it on the screen. Now, the user can either select one of those options, or click outside. If outside, then the matched results should close. If one of the options is selected, then the whole code in the middle runs.
The problem is that the matched results overlays on top of another div that if it is clicked on, something else will happen. When I click on the matched results, then the code registers as clicking on the outside (so the matched selected disappears, and the effect is as though I clicked on the other div that I don't want to click on.
So my solution was to place a timer before the click on the outside is executed. It all works fine, except clearInterval does not clearout the timer!! So the second time I load something, it is as though the timer was not cleared!
WhY?!
You're overriding timeOutTask with a new interval. You can cache the intervals to an array, something like this:
var timeOutTasks = [];
$('body').on({
...
el.bind('blur', function(){
timeOutTasks.push(setInterval(function(){
clearInterval(timeOutTasks.pop());
...
}, 500);
...
}
...
}
Related
I've implemented the Leaflet search-box extension.
Whenever I use the mouse to pan around on the map, the search box dissappears immediately and the user has to re-type the entire query every time.
I'd like the search-box and it's query to hang around until the user presses the clear button.
A display:block; is added and removed in order to show/hide the search-box. I'd like to only allow the collapse to happen when the user clears the query, instead of on any mouse movement.
Alternatively I've tried to keep the query around so the user doesn't have to re-type it every time. By catching the collapse event and storing the query. But at that point the box has already been cleaned up and there's no text to remember.
var timeout = {};
var oldQuery = "";
controlSearch.on('search:expanded', function () {
var searchBox = this._input;
searchBox.value = oldQuery;
this._input.onkeyup = function () {
clearInterval(timeout);
timeout = setTimeout(function () {
var query = searchBox.value;
search(query, searchItems, searchResultsLayer);
if (query.length > 0) {
if (!searchResultsShown) {
searchResultsLayer.addTo(map);
}
}
else {
if (searchResultsShown) {
searchResultsLayer.removeFrom(map);
}
}
}, 200);
};
}).on('search:collapsed', function () {
oldQuery = this._input.value;
});
To keep the user input you have to remove :
this.cancel();
From :
collapse: function() {
}
To keep the search box from collapse you can add the option collapsed to false like this example :
map.addControl( new L.Control.Search({
container: 'findbox',
layer: markersLayer,
initial: false,
collapsed: false
}) );
Then when you click on clear you should fire the collapse function and everything should work fine.
Following code snippet to show the core structure:
EDIT1:
var smthing = 0;
change_name_button.addEventListener('click', function(event){
// some query
// .....
// result from query
data = res.name.coords;
// tried to make the function go to GC
smthing = null;
delete smthing;
smthing = new drawMouseMovement(data);
event.stopPropagation();
}, false);
function drawMouseMovement(data){
// bunch of variables set for drawing function
// .....
// .....
var test = 0;
// draw something to canvas until end "maxLength" is reached
var draw = function() {
if(t < maxLength){
// redraw some stuff to canvas
// .....
}else{
return;
}
}
// function to play pause and replay the drawing on canvas
function playPause(boolPP, boolRP){
if(boolPP){
test = setInterval(draw, 10);
}else{
clearInterval(test);
}
if(boolRP){
// some params being reset
// .....
test = setInterval(draw, 10);
}
}
function play(event){
playPause(true, false);
event.stopPropagation();
}
function pause(event){
playPause(false, false);
event.stopPropagation();
}
function replay(event){
playPause(false, true);
event.stopPropagation();
}
play_button.addEventListener('click', play, false);
pause_button.addEventListener('click', pause, false);
replay_button.addEventListener('click', replay, false);
}
Everytime the change_name_button is clicked drawMouseMovement() is called with new parameters.
Following problem: When the draw function does not reach return before clicking change_name_button again, there are two instances of the same function drawing two different things at the same time. Only the last called instance of the function should be drawing.
I tried deleting the pointer to the function, clearInterval() and removeEventListener. But I don't seem to get any of those to work.
I hope my problem is clear.
Thanks in advance.
EDIT
A simple replication of the problem. Is some_button clicked once, smt is printed every 250ms. Is some_button clicked a second time, smt is printed every 125ms etc. How do I overwrite the first instance of printer() with the next click?
some_button.addEventListener('click', foo, false);
function foo(event) {
printer();
event.stopPropagation();
}
function printer(){
setInterval(function() {
console.log("smt");
}, 250);
}
UPDATE 2
A simple replication of the problem. Is some_button clicked once, smt is printed every 250ms. Is some_button clicked a second time, smt is printed every 125ms etc. How do I overwrite the first instance of printer() with the next click?
No way! Don't kill the function, let it ride. First you need a counter to count the clicks so the function knows it's been clicked the second time. Second, just add extra behavior for when the button is clicked the second time, in this case, you are going to half the time interval.
Ok, when I said JavaScript time is quircky, I meant fu##3d. setInterval needs clearInterval to stop it. What most articles and tutorials fail to say is that the damn setInterval still exists, so making it null will allow you to create a new one. I decided to make a constructor timer.
The demo has a button, click it and it'll print out 'smt' every 2 seconds plus the number of clicks to start a new interval.
The 'Go' button is replaced by a 'Stop' button, once clicked it does as advertised--stops
Click it again and it's the 'Go' button, but this time, it is printing every second now.
Lather, rinse, repeat.
Refactor this demo with some prototype wizardry and you got yourself a class.
PLUNKER - TIMER CONSTRUCTOR
PLUNKER - 1 EVENTLISTENER, MULTIPLE EVENT.TARGETS
SNIPPET
<!DOCTYPE html>
<html>
<head>
<style>
.on { display: block; }
button { display: none; }
</style>
</head>
<body>
<button id="btn1" class="on">Go</button><button id="btn2" class="">Stop</button>
<script>
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var counter = 0;
var timer = new Timer();
btn1.addEventListener('click', xStart, false);
btn2.addEventListener('click', xStop, false);
function xStart(event) {
timer.term;
counter++;
timer.start(counter);
btn1.classList.toggle('on');
btn2.classList.toggle('on');
event.stopPropagation();
}
function xStop(event) {
timer.term();
btn1.classList.toggle('on');
btn2.classList.toggle('on');
event.stopPropagation();
}
function Timer(c){
var self = this;
self.start = function(c){
var t = self.printer(c);
self.interval = setInterval(function() { self.printer(c); },t);
};
self.term = function(){
self.clear = clearInterval(self.interval);
self.null;
};
self.printer = function(x){
var d = (x % 2 === 0) ? 2 : 1;
var t = 2000 / d;
console.log('smt'+x+' t: '+t);
return t;
};
}
</script>
</body>
</html>
UPDATE 1
The following Plunker demonstrates how you can make the only eventListener the element that your buttons all share as the parent.
PLUNKER
OLD
None of your eventListeners() have anything for capturing phase, although I believe it's false by default, try setting it to false anyways.
change_name_button.addEventListener('click', function(event){
// some query
// .....
// result from query
data = res.name.coords;
// tried to make the function go to GC
smthing = null;
delete smthing;
smthing = new drawMouseMovement(data);
event.stopPropagation();
}, false);
^^^^^^^^====== There is the capturing phase`
Use event.stopPropagation(); on the other eventhandlers as well and place close to the end of handler. Don't forget to pass the (event) object.
function play(event){
playPause(true, false);
event.stopPropagation();
}
function pause(event){
playPause(false, false);
event.stopPropagation();
}
function replay(event){
playPause(false, true);
event.stopPropagation();
}
play_button.addEventListener('click', play, false);
pause_button.addEventListener('click', pause, false);
replay_button.addEventListener('click', replay, false);
Also, if that doesn't fix the issue then you need to post the HTML because the layout of your event.target and event.currentTarget might have to be adjusted.
EDIT
Try changing the if else
function drawMouseMovement(data){
// bunch of variables set for drawing function
// .....
// .....
var test = 0;
// draw something to canvas until end "maxLength" is reached
var draw = function() {
if(t < maxLength){
// redraw some stuff to canvas
// .....
}
// when t has reached maxlength, then it should quit?
return false;
}
This seems like something that should be really simple. I have a few images animating on a page, but I want the user to be able to click on any one of them at any time and then go to a related page.
Problem is, evidently clicks stopped being listened for at some point if I use a loop to search through an array of clickable items. I thought having a function separate from the one that handles the animation would allow it to constantly listen no matter what the animated images were doing, but it seems once the "complete" function is called (for the "animate" function), the function that is listening for clicks (wholly separate from the animation, and using setInterval to listen for clicks) stops listening.
Oddly enough, I believe I did not have this problem when just listening for "img" instead of an array of different images.
Ideas as to what I'm doing wrong? More info needed? I tried to remove any irrelevant code below.
var links = ["#portfolio", "#animations", "#games"];
$(function() {
setInterval(function(){
for (var i=0; i<links.length; i++) {
$(links[i]).click(function(){
window.location.replace("http://www.gog.com");
});
}
}, 500);
});
$(document).ready(function() {
links.forEach(function(current){
//various vars
var link = $(current);
var footer3 = $(".footer3");
var over = true;
var randomTime = 3000*(Math.random()+1);
//dust vars
...
//image vars
var imageUrlShadow = 'images/home/non-char/shadow-pngs/shadow';
var imageUrlCharacter = 'images/home/char-pngs/';
var portfolioSrc;
var animationsSrc;
var gamesSrc;
//animate the characters
link.animate({
top: '0'
}, {
duration: randomTime,
easing: 'easeOutBounce',
step: function(now, tween) {
/*handle shadows*/
...
/*handle characters*/
if (now < -25 && over == false) {
...
} else if (now >= -25) {
...
}
$("#"+ link.data("portfolio")).attr('src', portfolioSrc);
$("#"+ link.data("animations")).attr('src', animationsSrc);
$("#"+ link.data("games")).attr('src', gamesSrc);
/*handle dust*/
var dustDoneMoving = '-50px';
var dustNotMoving = '0px';
//if link is NOT touching footer3
...
//set to "sitting" images when animation is done
complete: function() {
...
setTimeout(function() {
...
}, 1000);
}
})
})
});
var links = ["#portfolio", "#animations", "#games"];
$(function() {
$(links.join(',')).click(function(){
window.location.replace("http://www.gog.com");
});
});
One time only and listener will be attached to the image.
Consider listening via window
var links = ["#portfolio", "#animations", "#games"];
$(window).on('click', links.join(', '), function() {
// do what you wanna
});
I apologize, it turns out that, apparently, the problem was related to the z-index. There were some other divs with 0 opacity "covering up" the array divs.
Setting the z-index to 2 for the array items has fixed the matter. Again, my apologies.
I have modified your code. See, if this works now.
I have added one more array which contains some URLs. So, the intention is that on click of a particular element, its respective URL should be opened.
So, the sequence in these array will matter with respect to each other.
Also, I have made use of 'on', so that 'click' event should be handled even during animation.
var links = ["#portfolio", "#animations", "#games"];
var sites = ["http://www.gog.com", "http://www.gog1.com", "http://www.gog2.com"]; //change these to the expected URLs
$(function() {
for (var i=0; i<links.length; i++) {
$(document ).on("click",links[i],function(){
window.location.replace(sites[i]);
});
}
});
I was wondering if there is a function to be run after an element (e.g. div class="myiv") is hovered and check every X milliseconds if it's still hovered, and if it is, run another function.
EDIT: This did the trick for me:
http://jsfiddle.net/z8yaB/
For most purposes in simple interfaces, you may use jquery's hover function and simply store in a boolean somewhere if the mouse is hover. And then you may use a simple setInterval loop to check every ms this state. You yet could see in the first comment this answer in the linked duplicate (edit : and now in the other answers here).
But there are cases, especially when you have objects moving "between" the mouse and your object when hover generate false alarms.
For those cases, I made this function that checks if an event is really hover an element when jquery calls my handler :
var bubbling = {};
bubbling.eventIsOver = function(event, o) {
if ((!o) || o==null) return false;
var pos = o.offset();
var ex = event.pageX;
var ey = event.pageY;
if (
ex>=pos.left
&& ex<=pos.left+o.width()
&& ey>=pos.top
&& ey<=pos.top+o.height()
) {
return true;
}
return false;
};
I use this function to check that the mouse really leaved when I received the mouseout event :
$('body').delegate(' myselector ', 'mouseenter', function(event) {
bubbling.bubbleTarget = $(this);
// store somewhere that the mouse is in the object
}).live('mouseout', function(event) {
if (bubbling.eventIsOver(event, bubbling.bubbleTarget)) return;
// store somewhere that the mouse leaved the object
});
You can use variablename = setInterval(...) to initiate a function repeatedly on mouseover, and clearInterval(variablename) to stop it on mouseout.
http://jsfiddle.net/XE8sK/
var marker;
$('#test').on('mouseover', function() {
marker = setInterval(function() {
$('#siren').show().fadeOut('slow');
}, 500);
}).on('mouseout', function() {
clearInterval(marker);
});
jQuery has the hover() method which gives you this functionality out of the box:
$('.myiv').hover(
function () {
// the element is hovered over... do stuff
},
function () {
// the element is no longer hovered... do stuff
}
);
To check every x milliseconds if the element is still hovered and respond adjust to the following:
var x = 10; // number of milliseconds
var intervalId;
$('.myiv').hover(
function () {
// the element is hovered over... do stuff
intervalId = window.setInterval(someFunction, x);
},
function () {
// the element is no longer hovered... do stuff
window.clearInterval(intervalId);
}
);
DEMO - http://jsfiddle.net/z8yaB/
var interval = 0;
$('.myiv').hover(
function () {
interval = setInterval(function(){
console.log('still hovering');
},1000);
},
function () {
clearInterval(interval);
}
);
I wrote a slideshow plugin, but for some reason maybe because I've been working on it all day, I can't figure out exactly how to get it to go back to state one, once it's reached the very last state when it's on auto mode.
I'm thinking it's an architectual issue at this point, because basically I'm attaching the amount to scroll left to (negatively) for each panel (a panel contains 4 images which is what is currently shown to the user). The first tab should get: 0, the second 680, the third, 1360, etc. This is just done by calculating the width of the 4 images plus the padding.
I have it on a setTimeout(function(){}) currently to automatically move it which works pretty well (unless you also click tabs, but that's another issue). I just want to make it so when it's at the last state (numTabs - 1), to animate and move its state back to the first one.
Code:
(function($) {
var methods = {
init: function(options) {
var settings = $.extend({
'speed': '1000',
'interval': '1000',
'auto': 'on'
}, options);
return this.each(function() {
var $wrapper = $(this);
var $sliderContainer = $wrapper.find('.js-slider-container');
$sliderContainer.hide().fadeIn();
var $tabs = $wrapper.find('.js-slider-tabs li a');
var numTabs = $tabs.size();
var innerWidth = $wrapper.find('.js-slider-container').width();
var $elements = $wrapper.find('.js-slider-container a');
var $firstElement = $elements.first();
var containerHeight = $firstElement.height();
$sliderContainer.height(containerHeight);
// Loop through each list element in `.js-slider-tabs` and add the
// distance to move for each "panel". A panel in this example is 4 images
$tabs.each(function(i) {
// Set amount to scroll for each tab
if (i === 1) {
$(this).attr('data-to-move', innerWidth + 20); // 20 is the padding between elements
} else {
$(this).attr('data-to-move', innerWidth * (i) + (i * 20));
}
});
// If they hovered on the panel, add paused to the data attribute
$('.js-slider-container').hover(function() {
$sliderContainer.attr('data-paused', true);
}, function() {
$sliderContainer.attr('data-paused', false);
});
// Start the auto slide
if (settings.auto === 'on') {
methods.auto($tabs, settings, $sliderContainer);
}
$tabs.click(function() {
var $tab = $(this);
var $panelNum = $(this).attr('data-slider-panel');
var $amountToMove = $(this).attr('data-to-move');
// Remove the active class of the `li` if it contains it
$tabs.each(function() {
var $tab = $(this);
if ($tab.parent().hasClass('active')) {
$tab.parent().removeClass('active');
}
});
// Add active state to current tab
$tab.parent().addClass('active');
// Animate to panel position
methods.animate($amountToMove, settings);
return false;
});
});
},
auto: function($tabs, settings, $sliderContainer) {
$tabs.each(function(i) {
var $amountToMove = $(this).attr('data-to-move');
setTimeout(function() {
methods.animate($amountToMove, settings, i, $sliderContainer);
}, i * settings.interval);
});
},
animate: function($amountToMove, settings, i, $sliderContainer) {
// Animate
$('.js-slider-tabs li').eq(i - 1).removeClass('active');
$('.js-slider-tabs li').eq(i).addClass('active');
$('#js-to-move').animate({
'left': -$amountToMove
}, settings.speed, 'linear', function() {});
}
};
$.fn.slider = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
return false;
}
};
})(jQuery);
$(window).ready(function() {
$('.js-slider').slider({
'speed': '10000',
'interval': '10000',
'auto': 'on'
});
});
The auto and animate methods are where the magic happens. The parameters speed is how fast it's animated and interval is how often, currently set at 10 seconds.
Can anyone help me figure out how to get this to "infinitely loop", if you will?
Here is a JSFiddle
It would probably be better to let go of the .each() and setTimeout() combo and use just setInterval() instead. Using .each() naturally limits your loop to the length of your collection, so it's better to use a looping mechanism that's not, and that you can break at any point you choose.
Besides, you can readily identify the current visible element by just checking for .active, from what I can see.
You'd probably need something like this:
setInterval(function () {
// do this check here.
// it saves you a function call and having to pass in $sliderContainer
if ($sliderContainer.attr('data-paused') === 'true') { return; }
// you really need to just pass in the settings object.
// the current element you can identify (as mentioned),
// and $amountToMove is derivable from that.
methods.animate(settings);
}, i * settings.interval);
// ...
// cache your slider tabs outside of the function
// and just form a closure on that to speed up your manips
var slidertabs = $('.js-slider-tabs');
animate : function (settings) {
// identify the current tab
var current = slidertabs.find('li.active'),
// and then do some magic to determine the next element in the loop
next = current.next().length >= 0 ?
current.next() :
slidertabs.find('li:eq(0)')
;
current.removeClass('active');
next.addClass('active');
// do your stuff
};
The code is not optimized, but I hope you see where I'm getting at here.