I have a piece of code like following:
$('.cardButton').click($.debounce(1500, function () {
console.log("OK");
}));
The debounce in this case works just perfectly..
However - I need to add animation function which will replace ".cardButton" element before the debounce occurs...
Doing something like this:
$('.cardButton').click($.debounce(1500, function () {
StartAnimationLoader();
console.log("OK");
}));
// In this case - animation starts as soon as console writes out "OK" ...
Or like following:
$('.cardButton').click(function(){
StartAnimationLoader();
$.debounce(1500, function () {
console.log("OK");
})
});
// When I execute code like this - there is nothing written in the console... - thus this method doesn't works
I need to execute animation before debounce occurs ...
What am I doing wrong here?
Can someone help me out ?
Adding a 2nd (or more) event handler to the same element will fire both events (unless stopped) so you can create two actions by having two separate event handlers:
// existing debounce fire only after user stops clicking
$('.cardButton').click($.debounce... );
// additional event will fire on every click
$(".cardButton").click(function() { StartAnimationloader() });
Related
I'm creating a typing test page and running into a small issue.
I'm trying to start the timer when the user types, and using onInput works, but the problem is that it registers every time I type into the textArea which causes the starttimer function to repeat itself.
onChange works but it only works after I click outside the page which makes sense, but is not what im looking for. I need the timer to start as soon as the user starts typing. Also with onChange the stop function works, but the timer starts after i click outside of the page.
Is there a JS event that fits what i'm looking for, or is there a way to change onInput or onChange to fix the problem i'm having.
JavaScript
document.getElementById("test-area").onchange = function () {
startTimer(1);
};
Thank you.
You need to listen to the input event because as you said change is only triggered after the input loses focus which is not what you want. You also need to handle the event only once.
document.getElementById("test-area").addEventListener("input", () => {
startTimer(1);
}, {once: true});
Note that this removes the event handler after it is fired. If you need to run it again you will have to register the event one more time. Maybe in your timer callback.
Try like this, In JavaScript, using the addEventListener() method:
The addEventListener() method attaches an event handler to the specified element.
document.getElementById("test-area").addEventListener("change", function () {
if(!this.value.length){
startTimer(1);
}
}, {once : true});
Have you tried onfocus ? its not exactly when they start typing but it works. Another option would be that you use onInput and on the clocks start function change a boolian -isRunning - to true. then put a if (isRunning) return. something like:
function start() {
if(isRunning) return;
isRunning = true;
}
and then change the boolian to false when you stop onChange
Some solutions:
Variant 1
Just create a flag:
var timerStarted = false; // Was the timer started?
document.getElementById("test-area").oninput = function () {
if(timerStarted) return; // If timer was started - do nothing
startTimer(1); // Else - start the timer
timerStarted = true; // Remember what we've started the timer
};
Variant 2
(A bit shorter)
document.getElementById("test-area").addEventListener("input", function () {
startTimer(1);
}, {once: true}); // Good thing about addEventListener
// With this it will run the event only single time
More here: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
Can you use JQuery? If so it has a method .one() which will execute the function only once. You can freely use keydown/keyup event handler then. For eg.
<script>
$(document).ready(function(){
$("#test-area").one("keydown", function() {
alert("hey");
});
});
</script>
I'm binding then unbinding the ready event listener to the document.
$(document).bind("ready", readyEventHandler);
function readyEventHandler() {
// run some code
$(document).unbind("ready");
}
The code produces no errors and will work. However, my javascript is cached and duplicates the code so I'll end up with having this code run more than once if I go back and then forward a page in the browser. When this happens, the ready event listener is not called at all. Am I properly unbinding this event listener? I know the caching issue becomes problematic(it's own separate issue) but I just want to bind the ready event listener, have it run code, then unbind it.
Not so sure it will help, but here are my 2 cents - instead of trying to unbind the readyEventHandler - make sure that if you run the function once it will not run twice:
var readyHandlerRun = false;
$(document).bind("ready", readyEventHandler);
function readyEventHandler() {
if (readyHandlerRun) {
return;
}
readyHandlerRun = true;
// Rest of your code...
}
Another options that popped just now:
$(document).bind("ready", readyEventHandler);
function readyEventHandler() {
readyEventHandler = function() { }
console.log('ready');
// Rest of your code...
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
UPDATE (by #jason328)
After talking with Dekel he provided me the appropriate answer.
$(document).bind("ready", function() {
readyEventHandler();
readyEventHandler = function() { }
});
Elegant and works like a charm!
if you just would like to use an eventhamdler only once, you could use one instead of bind
$(document).one("ready", function() {
// code to run on document ready just for once
});
Simplified scenario:
I have a click event on a button
Inside the event I call a function X
Function X returns a value
Click event changes DOM using received data (actually renders a jQuery Template)
SAMPLE CODE:
$("button").click(function()
{
var response = FunctionX();
doTemplateRendering(response); //(*)
});
function FunctionX()
{
//some code
return some_value;
//The click event has finished, so now make a little adjust to the generated dom (*)
}
The questions are:
Do I have a way to determine when the click stops form FunctionX()?
Or is there a way that doTemplateRendering() triggers something that I can capture from FunctionX() so it doesn't matter if I return a value, because at some point I'm going to be able to execute the extra code that I need
The reason behind this is that this is part of a framework and I can't change the click event.
You can't return a value from a function and then do further processing within the same function. But you can schedule some code to run later using setTimeout():
function FunctionX()
{
//some code
setTimeout(function() {
//The click event has finished, so now make a little adjust to the generated dom (*)
}, 5);
return some_value;
}
JS is single-threaded (if we ignore web-workers), so the function you pass to timeout won't be executed until after the click event finishes.
Alternatively, you can bind a second click handler to the same button and do your extra processing there - jQuery guarantees that event handlers (for the same event and element) will be run in the order that they're bound.
Not sure if this works for you, but couldn't you use a callback function that you pass to FunctionX?
$("button").click(function()
{
var fn = funcion(){response){
doTemplateRendering(response);
}
FunctionX(fn);
});
function FunctionX(fn)
{
//some code
fn(some_value);
//The click event has finished, so now make a little adjust to the generated dom (*)
}
I have the following code;
$("#myID").click(function () {
//do something
})
At some point, a user action on another part of the webpage needs to change the action that occurs on the click e.g.
$("#myID").click(function () {
//do something different
})
My question is, what's the correct/most efficient way of doing this? Currently I'm just implementing the second chunk of code above, but will this cause some odd behaviour? i.e. will there now be two different actions performed on click? Or does the second block of code override the first.
They will both execute so no, the second call does not overwrite the first.
Basic jsFiddle example
And as pimvdb notes, they will be executed in the order they were bound.
You can always unbind the click function first: http://api.jquery.com/unbind/
Right, they "stack". I.e. $("#myID") will maintain a list of event handlers, and execute both on click.
If you no longer want the original handler, you need to unbind it, using $("#myID").off('click') or if you're using an old version of jquery, $("#myID").unbind('click')`. http://api.jquery.com/unbind/
In your code, both clicks will be executed.
Try to unbind click event before
$("#myID").unbind("click")
http://api.jquery.com/unbind/
You can add a global variable isAnotherEvent = false and then check on click event which part of code you need to execute, to execute another part simply make isAnotherEvent = true
var isAnotherEvent = false;
$("#myID").click(function () {
if(!isAnotjerEvent){
//do something
} else {
//do something else
}
})
$("#btnChangeEvent").click(function(){
isAnotherEvent = true;
}
I've been stuck on this issue for about 2 days. My code (JSFiddle here) is thus:
var foo = function(){
// The code in here will be execute more and more and more times
$(element).hover(function() {
console.log("buggie code run")
})
}
var sliderShow = $(secondElement).bxSlider({
onAfterSlide:function(currentSlideNumber) {
$.ajax("/echo/html/").done(function() {
foo();
})
}
})
My problem is the code will run more than once. For example, when you hover over the element it will fire the function once, but second time it will fire twice. The third time it will fire 3 times, and so on. Why is this happening? Am I making a basic logic error, or is this JavaScript doing something?
This means you are registering the event more than once, probably on each load. You should do so only once!
Hovering itself calls the function twice once on entry and once on exit.. try
var foo = function(){
$(element).hover(function() {console.log("IN")},function() {console.log("OUT")});
}
But then as ThiefMaster pointed out you are also registering the eventhandler multiple times. In you slider, the second time you will add the event handler again and so on and on.
Look at http://docs.jquery.com/Namespaced_Events