I want to turn off the onclick till the function that was called by the onclick is done. How can I do that? But I don't want to turn off the onclick forever
function move() {
//do things...
$("#carr").off("click");
}
dado.onclick = move;
While you can add and remove eventListeners, it might be a better idea to add a guard for the function invocation, e.g.
var isRunning = false;
function myFunction(e, cb) {
// do stuff
return cb();
}
function guard(functionToRun, e) {
if (isRunning) {
return;
}
isRunning = true;
functionToRun(e, function() {
isRunning = false;
});
}
$someNode.on('click', guard.bind(this, myFunction));
You are on the right track. Use JQuery's bind and unbind functions:
function move() {
$("#carr").unbind("click");
//do stuff
$("#carr").bind("click", function () {
move();
});
}
$(document).ready(function () {
move();
});
Related
Here is my pseudocode:
if(key.pressed = 'a') {
activate = true;
}
var mytimeout = function timer_function() {
// Do stuff;
setTimeout( function() {
// do more stuff
}, 5000);
}
function some_function() {
if(activated) {
// do stuff
clearTimeout(mytimeout);
timer_function();
}
}
if(mouse.click == true) {
some_function();
}
I want the timer to be reset on each mouse click which calls some_function(). What actually happens is that the time is set on first click but never resets after that.
What am I missing?
Thanks.
mytimeout is a function, not a timeout handle. What you need to store is the result of the setTimeout call like this.
var timeoutHandle;
function timer_function() {
// Do stuff;
timeoutHandle = setTimeout( function() {
// do more stuff
}, 5000);
}
function some_function() {
if(activated) {
// do stuff
clearTimeout(timeoutHandle);
timer_function();
}
}
In function timer_function return the value of setTimeout
var mytimeout = function timer_function() {
return setTimeout( function() {
//Do some more stuff
}, 5000);
}
Thats because in you are only going to replay the Timeout only when the user presses the "a" key. I don't know why you kept it like that but thats probably the reason.!
I would like to run a function, when a checkbox is checked and stop that function, when the checkbox is not checked.
This is how I tried it:
$('#auto').on('click', function() {
if ($(this).is(':checked')) {
// Interval
var autoInterval = window.setInterval(function() {
navi('next');
}, 1500);
}
else {
clearInterval(autoInterval);
}
});
The problem is clearInterval() does not work and I get no errors.
https://jsfiddle.net/n339tzff/9/
It will work if my code looks like this:
// Interval
var autoInterval = window.setInterval(function() {
navi('next');
}, 1500);
// Auto Play
$('#auto').on('click', function() {
if ($(this).is(':checked')) {
autoInterval;
}
else {
clearInterval(autoInterval);
}
});
But then I have another problem... I only want to run the function navi('next') when I click on the checkbox and not at the beginning.
When you click, it calls the setInterval and stores the result of the call in the autoInterval and after ending the function removes it. So you store and lost the value of your variable every time in the same call.
Declare the autoInterval variable outside of the event handler, to make it independent from the event handler's scope. Also you can wrap your function with a IIFE to not mutate this variable outside
(function() {
var autoInterval;
$('#auto').on('click', function() {
if ($(this).is(':checked')) {
autoInterval = window.setInterval(function() {
navi('next');
}, 1500);
} else {
clearInterval(autoInterval);
}
});
})();
You should define autoInterval outside of the event handler function, as after the event has run this variable would be 'discarded'/un-accessable.
var autoInterval = null;
$('#auto').on('click', function () {
if ($(this).is(':checked')) {
autoInterval = window.setInterval(function () {
navi('next');
}, 1500);
}
else if(autoInterval !== null) {
clearInterval(autoInterval);
autoInterval = null;
}
});
Is there any way to overwrite a function or event handling in function?
Using addEventListener, we can have as many event handlers on element as much we want
var test=document.getElementById("div");
test.addEventListener("click",function(){alert("im first");},false);
test.addEventListener("click",function(){alert("im second");},false); // alerts "im first" and after that "im second"
but what if we want to overwrite function/event for example based on client width for example something like this
function one() {
alert("first");
}
function two() {
alert("second");
}
window.onresize = function() {
var test = document.getElementById("div");
if (window.innerWidth > 500) {
test.onclick = one
} else {
test.onclick = two;
}
}
Is something like this possible in javascript?
In this case I would use very effective but very little known approach. addEventListener can accept an object with property handleEvent as event handler. In this case it's very easy to overwrite handler function, set it to null ot completely different function without messing with removeEventListener and addEventListener again and again.
In your case:
var test = document.getElementById("div");
var handlers = {
handleEvent: function () {
alert("im first");
}
};
test.addEventListener("click", handlers, false);
function one() {
alert("first");
}
function two() {
alert("second");
}
window.onresize = function() {
if (window.innerWidth > 500) {
handlers.handleEvent = one;
} else {
handlers.handleEvent = two;
}
}
Check the demo below, resize the pane to see how it dynamically picks up different handlers based on viewport width.
Demo: http://jsfiddle.net/dfsq/t4wrjkLa/
As long as you have a reference to the original handler function, you can call removeEventListener on it, and just add your own listener like normal.
function one()
{
alert('first');
}
var test = document.getElementById('test');
test.addEventListener('click', one);
// Later in your code
function two()
{
alert('second');
}
test.removeEventListener('click', one);
test.addEventListener('click', two);
Demo:
var button = document.getElementById('button');
button.addEventListener('click', function(event)
{
test.removeEventListener('click', one);
test.addEventListener('click', function()
{
alert('second');
});
event.target.parentNode.removeChild(event.target);
});
function one()
{
alert('first');
}
var test = document.getElementById('test');
test.addEventListener('click', one);
#test
{
background: #CCC;
border: solid 1px #666;
padding: 5px;
}
<div id="test">Click me</div> <button id="button">Exchange event listeners</button>
Look at this. You can remove the old event function then replace it with the new event function
function one() {
alert("first");
}
function two() {
alert("second");
}
window.onresize = function() {
var test = document.getElementById("div");
if (window.innerWidth > 500) {
try{
test.removeEventListener("click",two);
} catch{}
test.addEventListener("click",one,false);
}
else {
try{
test.removeEventListener("click",one);
} catch{}
test.addEventListener("click",two,false);
}
}
I would use a closure to reference the function currently set as the event handler:
var onResize = function () {
// references the current handler
var curr;
// removes/adds event handlers
function swap (curr, repl) {
var test = document.getElementById('div');
test.removeEventListener('click', curr);
test.addEventListener('click', repl);
}
// the "resize" event handler which will be
// assigned to the "onResize" variable
return function () {
if (window.innerWidth > 500) {
if (curr !== one) swap(curr, one);
curr = one;
}
else {
if (curr !== two) swap(curr, two);
curr = two;
}
};
}(); // IIFE
window.addEventListener('resize', onResize);
// run "onResize" at starting to
// set up one of the below handlers
onResize();
function one () { alert('first'); }
function two () { alert('second'); }
<div id="div">div</div>
is there any chance to create a function that i can call?
if i'm putting the following lines in the document ready function it works:
Caman("25-02-2014_16-37-13.jpg", "#example-canvas", function () {
this.brightness(brightness);
this.render(function () {
check = this.toBase64();
});
But if i'm doing this i can't call. So I tried this:
function icancall()
{
Caman("25-02-2014_16-37-13.jpg", "#example-canvas", function () {
this.brightness(brightness);
this.render(function () {
check = this.toBase64();
});
}
So i thought i can call this with icancall(); But nothing happened. What am I doing wrong?
What i want do: executing the Caman function on a button click.
I hope you can help me !
function resz(){
Caman("25-02-2014_16-37-13.jpg", "#example-canvas", function () {
try {
this.render(function () {
var image = this.toBase64();
xyz(image); // call that function where you pass filters
});
} catch (e) { alert(e) }
});
}
[Apply CamanJS filters by this function]
function xyz(image){
var filters_k = $('#filters');
filters_k.click(function (e) {
e.preventDefault();
var f = $(this);
if (f.is('.active')) {
// Apply filters only once
return false;
}
filters_k.removeClass('active');
f.addClass('active');
var effect = $.trim(f[0].id);
Caman(canvasID, img, function () {
if (effect in this) {
this.revert(false);
this[effect]();
this.render();
}
});
});
}
I'm new to JavaScript and I'm having problems with this script.
it's part of a web game and the script is suppose to refresh the page until the player wins or loses.
for some reason it doesn't stop refreshing, I put an alert function to check if the functions works, and i get the alerts but it's still continue refreshing the page.
what am i doing wrong?
var t;
$(document).ready(function () {
intervals();
});
function intervals() {
t = self.setInterval('refreshData()', 10000);
}
function youWin() {
var f = $('#status:contains("YOU ARE THE WINNER!")');
if (f.length > 0) {
alert("YOU ARE THE WINNER!");
t = clearInterval(t);
}
}
function youlose() {
var f = $('#status:contains("You lost!")');
if (f.length > 0) {
alert("You lost!");
t = clearInterval(t);
}
}
function refreshData() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame');
youWin();
youlose();
}
You need to fix the reference to self and fix the .load() call.
.load() is asynchronous so it does not complete before you call youWin() and youLose() right after it. You need a completion function so you can check winning or losing after the .load() completes successfully.
refreshData() should be structured like this:
function refreshData() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame', function() {
youWin();
youlose();
});
}
You also should change this:
t= self.setInterval('refreshData()',10000);
to this:
t = window.setInterval(refreshData, 10000);
I don't see that self was even defined so that could have also been causing your problem and you should use the function reference directly rather than put in a string.
And, as a cleanup issue, you should change both occurences of this:
t = clearInterval(t);
to this:
clearInterval(t);
Here's a cleaned up version of the code that also eliminates global variables and unnecessary function definitions:
$(document).ready(function() {
var t = window.setInterval(function() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame', function() {
youWin();
youlose();
});
}, 10000);
function youWin() {
if ($('#status:contains("YOU ARE THE WINNER!")').length) {
alert("YOU ARE THE WINNER!");
clearInterval(t);
}
}
function youlose() {
if ($('#status:contains("You lost!")').length) {
alert("You lost!");
clearInterval(t);
}
}
});