What I would like to do is if there is clicked at the 'reset' button, the value of a other button changes. I tried to use the document.getelementbyid property but it seems not to work. Does somebody know how I should implement this?
function reset() {
stop();
x.reset();
update();
opnieuw = setTimeout(function(){
document.getElementById("scherm3").style.display = "block";
document.getElementById("scherm2.2").style.visibility = "hidden";
}, 10000);
clearTimeout(timeOut);
clearTimeout(timeOutElse);
document.getElementById("buttontimer").value = "Start";
}
setTimeout(start, 5000);
function toggleTimer(event) {
if (isTimerStarted) {
stop();
event.target.value = 'Start';
timeOut = setTimeout(function(){
document.getElementById("scherm4").style.visibility = "visible";
document.getElementById("scherm2.2").style.visibility = "hidden";
}, 4000)
clearTimeout(opnieuw);
clearTimeout(timeOutElse);
}
else {
start();
event.target.value = 'Stop';
timeOutElse = setTimeout(function(){
document.getElementById("scherm3").style.display = "block";
document.getElementById("scherm2.2").style.visibility = "hidden";
}, 8000)
clearTimeout(timeOut);
clearTimeout(opnieuw);
}
}
and HTML:
<div id="button1"><input type="button" value="Stop" onclick="toggleTimer(event); clicks5times();" id="buttontimer"></div>
<input type="button" value="Opnieuw" onclick="reset()" class="button2" id="opnieuw">
You could probably just make your code simpler by simply having a "Start" and "Stop" button, separately, and just show/hide the correct button for the current context. You are already (sort of) doing this, by showing the "Reset" button. Just make this a "Stop" button. When they click "Start", the "Start" button is hidden and the "Stop" button is shown. Click "Stop", and "Stop" is hidden and "Start" is shown. You could even use a global boolean to track state and make the "Stop" button behave like a "Pause" button, and show an additional "Reset" button that puts the timer back to 0. That all depends on what, exactly, you are trying to accomplish.
Related
I have been working in a mini-game-project (Simons game) that many of you may know. Where the computer plays a random sequence of buttons in which players have to follow to go to the next level in the game e.g: [one click first round, two clicks second round..].
I already did all the button effects as well as make the machine plays buttons randomly in a range of ten rounds. So, what I would like to do is use a button to turn on and off the function that makes the computer clicks By Itself using a button.
I already tried using the jQuery function $(startButton).on('click', clickByItself); alone but it did not worked.
$(document).ready(function() {
//four variables representing its button effects
//button blue effect
var blueButtonEffect = code here;
var greenButtonEffect = code here;
var redButtonEffect = code here;
var yellowButtonEffect = code here;
//to be used on the buttonEffects()/clickByItself()
var arr = [blueButtonEffect, redButtonEffect, greenButtonEffect, yellowButtonEffect];
let enabled = true;
let times = 0;
//makes button effects play itself randomly
function clickByItself() {
let random = Math.floor(Math.random() * arr.length);
$(arr[random]).click();
if (++times < 10) {
setTimeout(function() { clickByItself(times); }, 1000);
}
}
clickByItself();
function turnOnTurnOff() {
if (enabled == true) { //TRYING TO TURN ON/OFF THE FUNCTION ON BUTTON CLICK..
$(startButton).on('click', clickByItself);
}else{
$(startButton).on('click', clickByItself);
}
}
Now, I am trying to use a function turnOnTurnOff() to see whether I could do the effect of turning on and off with the click of a the startButton. Thank you.
You can use .off() method of jQuery to remove an event listener as follows.
I added two divs for better demonstration.
One button binds and unbinds (toggles) the click handler of the second button using jQuery's .on() & .off(). When the click handler is bound to the second button, clicking it will update the div with a number. When the click handler is unbounded from the second button, clicking the second button will do nothing. Two lines of interest in the JavaScript code below are decorated with a comment each. The rest is for demonstration.
window.enabled = false;
window.count = 1;
// Initialize the view (for demo)
$(function() {
$('#switchIndicator').html(`<p>${enabled ? 'Switch is ON' : 'Switch is OFF'}</p>`);
$('#btn').html(enabled ? 'You can click me :-)' : 'You CANNOT click me');
});
// Toggle click functionality using jQuery's .on() & .off() methods
function toggle() {
enabled = !enabled;
if (enabled) {
// Line of interest #1: jQuery .on()
$('#btn').on('click', handleClick);
} else {
// Line of interest #2: jQuery .off()
$('#btn').off('click', handleClick);
}
$('#switchIndicator').html(`<p>${enabled ? 'Switch is ON' : 'Switch is OFF'}</p>`);
$('#btn').html(enabled ? 'You can click me :-)' : 'You cannot click me :-((');
$('#btn').removeClass(enabled ? 'disabled' : 'enabled').addClass(enabled ? 'enabled' : 'disabled');
}
function handleClick() {
$('#counter').append(` ${count++}`);
}
/* CSS */
#btn.enabled {
background-color: greenyellow;
}
#btn.disabled {
background-color: lightgray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="switchIndicator"></div>
<button id="switch" onclick="toggle()">On/OFF Switch</button>
<button id="btn"></button>
<div id="counter"></div>
Give this a try:
function clickByItself() {
if(enabled) {
let random = Math.floor(Math.random() * arr.length);
$(arr[random]).click();
if (++times < 10) {
setTimeout(function() { clickByItself(times); }, 1000);
}
}
}
clickByItself();
function turnOnTurnOff() {
if (enabled) {
enabled = false;
} else {
enabled = true;
clickByItself();
}
}
$(startButton).click(function() {
turnOnTurnOff();
});
You could do it in multiple ways. One is to use setInterval instead of setTimeout and store it inside a variable. When you need to stop it, just call clearInterval.
First I displayed the div on screen and now I want to use the the button to create that same div(or any other action) after user input.
document.getElementById("add").addEventListener("click", function() {
document.getElementById("welcome").style.display = "block";
}
How do i make the button be able to work again after the first thing it did?
It isn't customary to reuse a UI element in different ways as it tends to confuse the end user. But if you must...
document.getElementById("add").addEventListener("click", showWelcome);
function showWelcome() {
document.getElementById("welcome").style.display = "block";
document.getElementById("add").removeEventListener("click", showWelcome);
reassignButton();
}
function resassignButton(){
// some decision logic for next button function
document.getElementById("add").addEventListener("click", doNextThing);
}
function doNextThing(){
// removes eventlistener on add button. does whatever
}
You can use removeEventListener to remove the handler and then set a new one.
var ele = document.getElementById('btn');
ele.addEventListener("click", function click1(){
//Do stuff for the first click
this.innerHTML = "Click Me Again";
alert("Hello");
//Remove the event hendler
this.removeEventListener("click", click1, true);
//Attach handler for rest of clicks
ele.addEventListener("click", function click2(){
alert("You cicked again!");
}, true);
}, true);
<button id=btn>Click Me</button>
Although it's probably more practical to re-use a single event listener, as assigning and re-assigning event listeners can sometimes lead to memory leaks..
(()=>{
var ele = document.getElementById('btn');
var clicks = 0;
ele.addEventListener("click", function(){
if(clicks){
alert("Thanks for clicking again");
}else{
alert("Hello");
this.innerHTML = "Click again";
}
clicks++;
}, true);
})();
<button id=btn>Click Me</button>
You can make several methods and use these with the onclick attribute of button.
Also I advise you to use jQuery. It's easy and faster than JS.
I want a button to be disabled (only if Validators from "grpRegister" validation group aren't triggered) to prevent double submitting. I used JavaScript to disable the button on click. But that ALSO started to prevent the form from being submitted (with no validators triggered). I managed to work around it adding a small timer before the disabling of the button. This is the code:
var btn = document.getElementById("btnRegister");
btn.addEventListener("click", function () {
if (Page_ClientValidate("grpRegister")) {
var myVar = setInterval(function () { btn.disabled = true; clearInterval(myVar); }, 100);
}
});
With only 100ms delay, it worked. So my question is, ANY timer value works? And why this is happening, it can't be disabled immediately?
EDIT:
Just 1ms is enough to make it work. The following code DON'T work:
var btn = document.getElementById("ContentPlaceHolder1_btnRegistar");
btn.addEventListener("click", function () {
if (Page_ClientValidate("Registar")) {
btn.disabled = true;
}
});
If someone mouseovers a text box for a second, I want to show a div. But I don't want it to show if they just mouseover quickly as the mouse passes over the text box.
<input type="text" value="Fred" onmouseover="overit()">
<div id="dv" style="display:none">Jim</div>
var delay;
function overit()
{
delay = window.setTimeout('showme();', 1000);
}
function showme()
{
document.getElementById('dv').style.display = 'block';
}
Unless someone mouseovers the text box for a second, I don't want showme() to be called. How can I cancel showme() being called if the gap between mouseover and mouseout is not at least a second?
Fiddle at http://jsfiddle.net/S4jx4/
I don't want to use jquery
Your proposed solution almost works. Add an onmouseout listener on the input to cancel the timeout.
<input type="text" value="Fred" onmouseover="overit()" onmouseout="window.clearTimeout(delay);">
http://jsfiddle.net/TN952/
You know the function WILL be called after 1 second, so you don't really have to check if the gap is there, you just have to cancel the timeout when mouseleave happens. If it's already been called, it's been less than a second, and cancelling it doesn't affect anything.
var delay;
function overit()
{
delay = window.setTimeout('showme();', 1000);
}
function showme()
{
document.getElementById('dv').style.display = 'block';
}
function leaveit() {
window.clearTimeout(delay);
}
<input type="text" value="Fred" onmouseenter="overit()" onmouseleave="leaveit()">
<div id="dv" style="display:none">Jim</div>
http://jsfiddle.net/hXE28/
remove the inline javascript
<input type="text" value="Fred" id="txt" />
<div id="dv" style="display:none">Jim</div>
and use event listeners
var input = document.getElementById('txt'),
text = document.getElementById('dv'),
timer;
input.addEventListener('mouseenter', function() {
timer = setTimeout(showme, 1000);
}, false);
input.addEventListener('mouseleave', function() {
clearTimeout(timer);
}, false);
function showme() {
text.style.display = 'block';
}
FIDDLE
I have some code where I have a timer. Every 3 seconds the background changes colors, and when you hover the stop button, the color changer pauses, I have an onclick event that i am using in junction with the mouseout event but the mouseout event cancels out my onclick event. What can I do so that the onclic event works still after I move the mouse from the stop button?
Code: jsfiddle
<script>
var colors = new Array();
colors[0] = "green";
colors[1] = "blue";
colors[2] = "gray";
var i = 0;
var timer;
function changeOfPlans() {
timer = setInterval("colorChange()", 3000);
}
function colorChange() {
document.getElementById("one").style.backgroundColor = colors[i];
document.getElementById("two").style.backgroundColor = colors[i];
i++;
if (i == 3 || i > 3) {
//start over by setting i to 0
i = 0;
}
}
function stop() {
clearTimeout(timer);
}
</script>
You need to update the on click action so that it sets a variable. Then have the mouse out first check whether that variable is set before restarting the color changing. Demo.
I modified your JavaScript like so:
var stopped = false;
function changeOfPlans() {
if (!stopped) {
timer = setInterval("colorChange()",3000);
}
}
function fullstop() {
stopped = true;
stop();
}
Then I updated your onclick to call fullstop() instead of just stop(). Since I left the other stop() function the same, the hover-to-stop-move-away-to-restart functionality still works as you had it originally. All of the other JavaScript remains the same.
<button type="button" onmouseover="stop()" onmouseout="changeOfPlans()" onclick="fullstop()">Stop</button>
There are other ways of doing this -- enhzflep suggests a good one in the comments -- but this is the simplest.
You are using setInterval, so to cancel you need clearInterval not clearTimeout.
Also don't run it again on mouseout i guess:
onmouseout="changeOfPlans()"