Clearing a Function in JavaScript - javascript

This may seem like a simple question. I've tried to Google the answer, but I can't seem to find it so that's why I'm here for help. Part of the problem is that I can't really phrase the question properly, so I will try to explain it here. Here goes...
I have two functions in my JavaScript file (let's name them fn1() and fn2()). I am calling these functions using onclick in my HTML file. For example:
<span class="test" onclick="fn1();">Button #1</span>
<span class="test" onclick="fn2();">Button #2</span>
The functions work perfectly fine when a user clicks on their respective buttons. However, if a users clicks on Button #1, and then Button #2 - both functions are called/loaded simultaneously.
Question: How do I make it so that fn1() is disabled (or cleared) as soon as the user clicks on Button #2, which will load fn2()?
Thank you.

You can use jQuery way the noop method
Within fn1() function you should use $.noop() to empty the function fn2()
Or simply as you are calling it on onclick you can remove that attribute within that function. (I don't recommend to use this)
$('span.test').not($(this)).removeAttr('onclick');
But I extremely recommend to use namespace by which you can unbind the click event like the following instead of calling inline javascript:
The on method
$( "span.test" ).on( "click.something", function( event ) {
//do your stuff here
});
Later you can unbind the click event like this:
The off method
$("span.test").off("click.something");

The nice way: disable the fn2 button when you enter fn1 (rather than disabling the function). This also has a side effect of letting the user know that the button is not available. Disabled elements do not fire 'click' events.
$('span.test').not($(this)).prop('disable', true);
The not-so-nice-way: set a variable when you're in one function, and clear it when you exit. Return early from the functions if the variable is set.
The downright ugly way: unbind the onclick from the other buttons if one is clicked. This is so messy that you really don't want to do that.
The I-really-can't-recommend-it-less way: redefine the other functions with no-ops.

I don't know if I understand your question correctly and I don't have enough rep to comment
but if you want the user not to be able to press the second button until the first finishes execution then you could do the follwing
in the first line of your fn2() add the following line
document.getElementById("button1").disabled = true
but you should first give an id button1 to the first button
this will grey the button button1 when the user press the button
after your code finishes execution you should add:
document.getElementById("button1").disabled = false
this will make the button pressable again

u may try this with flags, this is not going to clear the function e.g.:
var runFn1 = true;
function fn1() {
if (!runFn1) {
return;
}
// ur code here
}
function fn2() {
runFn1 = false;
// ur code here
}

"The functions work perfectly fine when a user clicks on their respective buttons. However, if a users clicks on Button #1, and then Button #2 - both functions are called/loaded simultaneously."
javascript being single threaded. fn1() execution is first completed and then followed by fn2(). Hope you understand there will not be a case where both are called simultaneously.
For example
function fn1(){
while(true){
}
}
function fn2(){
alert("2");
}
<input type="button" value="Btn1" onClick="fn1();"/>
<input type="button" value="Btn2" onClick="fn2();"/>
Try invoking fn1(). you will be surprised fn2() cannot be invoked!

Related

JQuery alter flow by using alter dialog

I have the following function, if I use the alert dialog the Click section (1) is reached. if I remove the alert dialog the page is posted and the Click section (1) is never reacted. How can I i solve it?
$("#txtInput").change(function () {
alert('...');
$("#btn.ClientID").click(); // Click (1)
});
If you want the change event to call JavaScript function before posting back to the server. Then pass an event object into the function and then use preventDefault(). This stops the default behaviour.
$("#txtInput").change(function (e) {
e.preventDefault();
$("#btn.ClientID").click(); // Click (1) - It's unlikely "btn.ClientID" is the correct name of your button
});

Shortcut keys for Javascript game GUI

I've been making a simple javascript based OOP text game that uses string replacement and variable adjustments tied to button .onclick events. I've been asked to add hotkeys for easier access, and I've been struggling with how to do it.
First I tried using the JSQuery hotkeys script and the .bind command, but that seemed like it would be very time consuming as I'd have to recode every .onclick as a hotkey, and even with unbind, it was firing off every event tied to the key on the script.
I feel like the best way to do would be if I could code the keys to the gui, i.e. if when you pressed "1", it activated the .onclick of button 1, that way the hotkey would be static (except when the button is disabled), but I've no idea how to do that. I've just been using html buttons, (i.e. input type="button" value="" disabled="disabled" id="button1"), I suspect I'd need something more sophisticated?
Thanks in advance for any help, google has been useless.
[EDIT - General description of code]
The way the game works is very simple, via the calling of functions as new events with different text/buttons (and different onclick events tied to those buttons). As an example, the start screen code is:
function startScreen() {
$(document).ready(function () {
$('#text').html("Game title and info");
$('#button1').val("Start Game");
$('#button1').attr("disabled", false);
$("#button1").one("click", function () {
textClear();
buttonClear();
nameScreen();
});
$("#button2").val("Load Game");
$('#button2').attr("disabled", false);
$("#button2").one("click", function () {
textClear();
buttonClear();
loadData();
});
$("#button6").val("Settings");
$('#button6').attr("disabled", false);
$("#button6").one("click", function () {
textClear();
buttonClear();
settingsScreen();
});
});
}
Since the code executed by button one changes between functions, what the hotkey does as well, which was my problem with using the JQuery library code.
When a key is pressed then the event onkeypress is fired. This event provides some values like:
keyCode
charCode
which
So you could do something like:
window.onkeypress = function (event) {
// the keyCode value for the key 1 is 49, for the key 2 is 50
if (event.keyCode == 49) {
// execute the same code as clicking the button 1
console.log("The key 1 was pressed.");
} else if (event.keyCode == 50) {
// execute the same code as clicking the button 2
console.log("The key 2 was pressed.");
}
};
Now, when a user visits your website he could press the keys 1 or 2 on the keyboard and fire the same logic as clicking the buttons "1" and "2" (being something like <input id="button1">) with the left mouse taste.
If you have really a lot of hotkeys then this would be also tedious to type, but without knowing your code I can hardly give you a complete solution. I hope my answer can give you some idea how to proceed further.
EDIT:
Further reading on the topic:
http://unixpapa.com/js/key.html

jQuery .click function executes twice in a row

I'm working on my first program using jQuery, but I'm having an issue. I have a dialog pop up on pageLoad that asks the user to select a date and a turn. Right now, for debugging purposes, I have it alert every time .click() executes, and for some reason, it seems like it executes before the user clicks and immediately afterward.
There are three radio buttons, Turns 1, 2, and 3. When the user clicks Turn 1, the alert should say "1". When the user clicks Turn 2, the alert should say "2", etc. But for some reason, it alerts the previous value as well as the new one. I searched all of my code, and there is only one alert, so I can't figure out what is calling click() twice. I've tested it in IE and Chrome and it happened both times.
This is my .click() function:
$("#turn-radio")
.click(function () {
turnvalue = $("input[name='turn-radio']:checked").val();
alert(turnvalue);
});
If you check this jsfiddle, you'll see the rest of my code, which will hopefully make it easier to figure out what my problem is.
Thanks!
You need to change selector: as your radio button IDs are different and you were giving name as a selector that's why you were facing that problem:
$("input[name='turn-radio']")
.click(function () {
turnvalue = $("input[name='turn-radio']:checked").val();
alert(turnvalue);
});
Updated Fiddle
changing
$("#turn-radio") to $("#turn-radio label")
causes only one popup displaying the previous value
But, personally i would
$("#turn-radio input").change( function() { /* do stuff */ } )

onclick function executes without any click on JavaScript

I am working with some JavaScript and Ajax functions. I am going to put some code while I explain myself to be more clear.
I have this element: <div id="divTest" onclick="test()">YES</div>
When the user clicks the DIV, the function replaces the "YES" for something like this:
YES <input type="radio" name="testing" value="YES" onclick="test_2(this.value)" checked />
NO <input type="radio" name="testing" value="NO" onclick="test_2(this.value)" />
This allows the user to select again the right option. Then I want to replace the radiobuttons with new value, so when the user selects any option, the DIV replaces the "radio" options and displays the value selected (YES OR NO) as it was on the beginning.
At this point everything works perfect.
Here is my problem:
I want the DIV to have the onclick() as the beginning onclick="test()" so I do it from JavaScript giving it the property this way: div.onclick = function() { test();};. The function test() is executed even if the user does not click on the div. It executes both function right away and does not wait until there is a click on it.
Does anyone knows how can I make the function to wait until there is any click on it? Am I giving the onclick property incorrectly?
I hope I made myself clear.
Here are the functions:
function test() {
var div = document.getElementById("divTest");
//I DO NOT INCLUDE THE AJAX CODE BUT THE RESPONSE INCLUDE THE RADIO BUTTONS METIONED ABOVE
div.innerHTML = xml.responseText();
}
function test_2(newValue) {
div = document.getElementById("newValue");
div.innerHTML = newValue;
div.onclick = function() { test(); };
}
Yes, your problem is with div.onclick = here you are actually assigning a click action to your div! Which will execute when your page loads.
What you want is to assign an event listener like so.
div.addEventListener('click' function(){});
I have got the same problem and I found this page. I check the spec of addEventListener and I found out I typed an excessive pair of bracket.
Two ways to do this:
1.use anonymous function(that is without a name, defined just in time to use) like the above answer.
2. you can't add the bracket. simply use ('click', myfunction).
If you want to use parameter, wrap your function into an anonymous function. like this:
div.addEventListener('click', function(){myfunction(e){}}).
it's a little bit late, hope you can read it and solve your problem.

stop the jquery function after one execution

I have the function Nextthing that hides first iframe and shows the next one, but as you will see in the code of the function I did just for only one next iframe, so if he makes the action for the second iframe to hides it and shows the next iframes it will display but in the wrong place.
How can I make the function to stop after one running?
function Nextthing (){
$("#i").hide();
$('.table').eq(1).find('tbody tr').eq(2).after(
'<tr><td colspan=10><iframe class="iframe" src="/msg.html?msgId=' +
$('.table').eq(1).find('tbody tr').eq(2)
.find('td a').eq(0).text()+'&constant=1"></iframe></td></tr>);
}
UPDATE: as you can see that iframe is called from that page msg.html, well that page has an input and a submit button, and the function Nextthing is called in that button like this:
<input type="submit" onclick="parent.Nextthing();" />
When somebody presses the submit button in the iframe it will load the iframe of the next page of msg.html based on msgId, and I want this load to be only once...
you can use
.one() handler.. It will run the code once and stop the execution.
$('input[type=submit]').one('click', function() {
$("#i").hide();
$('.table').eq(1).find('tbody tr').eq(2).after('<tr><td colspan=10><iframe class="iframe"
src="/msg.html?msgId='+$('.table').eq(1).find('tbody tr').eq(2).find('td
a').eq(0).text()+'&constant=1"></iframe></td></tr>);
});
For this I usually just have a global variable such as elTriggers = false and check for that and make it true when it is triggered. You could also check out jquery's one function.

Categories

Resources