The variables in this Javascript code represent buttons that once they have been clicked will trigger an animation within a function to be determined later. For the animation to be triggered, all 5 buttons need to be clicked. That’s the part I am struggling with. The code represents the most I have been able to do so far (not very good at javascript). Can anyone point me in the right direction to solve this issue?
<script>
var homework= document.getElementById("homerwork");
var teeth= document.getElementById("teeth");
var reading= document.getElementById("reading");
var stuff= document.getElementById("stuff");
var good= document.getElementById("good");
homework.addEventListener("click", rightclick);
teehth.addEventListener("click",righclick);
reading.addEventListener("click", righclick);
stuff.addEventListener("click", righclick);
good.addEventListener("click", rigclick);
function rightclicks () {
//function that will trigger the animation//
}
</script>
It is not clear exactly what you want. If you want your function triggered within certain time interval, there is a js method setInterval();.
For example:
var a = function(){
if (current === sliderImages.length - 1) {
current = -1;
}
slideRight();
}
setInterval(a, 3000);
The code above triggers the function every 3 seconds.
You made some spelling errors(such as, function name). Added the runnable code. Here, all buttons are calling the same rightclick method. Hope this will help you to begin with.
var homework= document.getElementById("homerwork");
var teeth = document.getElementById("teeth");
var reading= document.getElementById("reading");
var stuff= document.getElementById("stuff");
var good= document.getElementById("good");
homework.addEventListener("click", rightclick);
teeth.addEventListener("click", rightclick);
reading.addEventListener("click", rightclick);
stuff.addEventListener("click", rightclick);
good.addEventListener("click", rightclick);
function rightclick () {
alert('hi');
// function that will trigger the animation
}
<html>
<head>
<title>Sample page</title>
</head>
<body>
<div class="wrapper">
<button id="homerwork">Homework</button>
<button id="teeth">Teeth</button>
<button id="reading">Reading</button>
<button id="stuff">Stuff</button>
<button id="good">good</button>
</div>
</body>
</html>
Set an attribute clicked of each html element in the click event handler. Then, check if each button has the attribute 'clicked', and if so call rightClicks()
Something like
var ids = ['homework', 'teeth', 'etc'];
function rightClick(event) {
event.target.clicked = true;
var allClicked = true;
for (var i = 0; i < ids.length; i++) {
var el = document.getElementById(ids[i]);
if (!document.getElementById(ids[i]).attr('checked')) {
allClicked = false;
}
}
if (allClicked) {
rightClicks();
}
}
I'm sure there is a simpler or superior way of doing this, but by building off of your original code snip—firstly fixing typos, second adding to the rightclick() function—I've created a solution only using Vanilla JS. Hopefully this gives you something to work with!
var homework= document.getElementById("homerwork");
var teeth= document.getElementById("teeth");
var reading= document.getElementById("reading");
var stuff= document.getElementById("stuff");
var good= document.getElementById("good");
homework.addEventListener("click", rightclick);
teeth.addEventListener("click", rightclick);
reading.addEventListener("click", rightclick);
stuff.addEventListener("click", rightclick);
good.addEventListener("click", rightclick);
function rightclick () {
this.setAttribute("clicked", true);
var buttons = document.getElementsByClassName("btns");
var numButtons = buttons.length;
var boolArray = [];
for(var key in buttons){
if(buttons[key].tagName == "BUTTON"){
boolArray.push(buttons[key].getAttribute("clicked"));
};
};
if(boolArray.length===numButtons){
if(boolArray.includes("false")){
return;
} else {
alert("all buttons clicked. go ahead with animation");
}
};
};
<html>
<head>
<title>Sample page</title>
</head>
<body>
<div>
<button class="btns" id="homerwork" clicked=false>Homework</button>
<button class="btns" id="teeth" clicked=false>Teeth</button>
<button class="btns" id="reading" clicked=false>Reading</button>
<button class="btns" id="stuff" clicked=false>Stuff</button>
<button class="btns" id="good" clicked=false>good</button>
</div>
</body>
</html>
Related
I have a jquery function that adds an event listener to various elements to execute on click. For some reason, when I try to reference a global variable (daySelected) inside the function, it says it is undefined. Am I missing something?
var daySelected = false;
$('.deal-day').bind('click', function(e) {
console.log("Day Selected: " + daySelected);
if (!daySelected) {
if($(this).hasClass('selected-filter')) {
$(this).removeClass('selected-filter');
var daySelected = false;
} else {
$(this).addClass('selected-filter');
var daySelected = true;
}
}
});
You have multiple var daySelected.
var should be defined only once. Otherwise you're creating new scopes.
As a general fix you could improve the code like:
let daySelected = false; // Feel free to change this boolean
const $dealDay = $(".deal-day"); // Get all buttons with that class
const toggleDaySelectedButtons = () => $dealDay.toggleClass("selected-filter", daySelected);
$dealDay.on("click", function(e) {
daySelected = !daySelected; // Toggle boolean
toggleDaySelectedButtons(); // Handle buttons
});
toggleDaySelectedButtons(); // Do on DOM ready
.selected-filter {background: gold;}
<button type="button" class="deal-day">Filter deal day</button>
<hr>
<button type="button" class="deal-day">Filter deal day</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
I really hope you have only one .deal-day button - otherwise the above will not be ideal
<html>
<body>
<button onclick = 'click1()'> </button>
</body>
<script>
var one
function click1(){
one = one + 1;
}
if (one == 3){
document.write('yes')
}
</script>
</html>
Here is an example JS / HTML. How can I write yes if the button is clicked three times?. This code would work in python and other languages. How can I do this in JS?
Your code have syntax and logical errors
<html>
<body>
<button onclick='click1()'>click here </button>
<script>
var one = 0;
function click1(){
one = one + 1;
if (one == 3){
alert("here");
}
}
</script>
</body>
</html>
after three clicks you will again have to reset variable one in if statement
if (one == 3){
alert("here");
one = 0;
}
There are multiple issues here.
First of all you should set a default to the variable, otherwise it will be declared as undefined.
Second you should put your if in the same function.
Third you should call your functions with the brackets in your html => 'click1()'
I also recommend making some changes
make your variable a let instead of a var.
use typesafe checks with 3 equal signs
<html>
<body>
<button onclick = 'click1()'> </button>
<script>
let one = 0;
function click1(){
one += 1;
if (one === 3){
document.write('yes')
}
}
</script>
</body>
</html>
var one = 0;
function click1() {
one++
if (one == 3) {
console.log('yes');
one = 0
}
}
<button onclick ='click1()'> </button>
Change your code like this:
<html>
<body>
<button onclick="click1()">Click</button>
</body>
<script>
var one = 0;
const click1 = () => { if (++one === 3) document.write('yes') };
</script>
</html>
Looks like you're missing the brackets on the function call on your button. Try: onclick='click1()'
You could use an approach like below. See the code comments for details:
// Reference to the DOM elements
const countEl = document.querySelector('#count-el');
const buttonEl = document.querySelector('button');
// Init a counter variable and return a function that increments it
const increment = (() => {
let i = 1;
return () => i++;
})();
// The click event listener
buttonEl.addEventListener('click', () => {
// Increment the count and update the UI based on if current click count is 3
if (increment() === 3) {
countEl.textContent = 'yes';
}
});
<span id="count-el"></span>
<br />
<button>Click 3 times</button>
I have a question about my code. What I'm trying to do is if a certain button is clicked and it isn't clicked again within 4 seconds, a element will be showed and another element hide. But if it is clicked within 4 seconds, it stays the same and so on. I think I should use SetInterval() and ClearInterval(). Currently I have two other functions that do other things. Maybe I can my function there?
Hopefully I have made it clear.
Current javascript code:
var clicks = 0;
function clicks5times() {
clicks = clicks+1;
if(clicks == 6){
document.getElementById('scherm3').style.display = 'block';
document.getElementById('scherm2.2').style.display = 'none';
}
}
var clicked = false;
setInterval(function(){
if (!clicked) {
document.getElementById("scherm4").style.visibility = "visible";
document.getElementById("scherm2.2").style.visibility = "hidden";
}
},13000);
document.getElementById("buttontimer").addEventListener("click", function(){
clicked = true;
});
Rather than set interval, I would say a timer would be better. Eg:
var clickTimer;
function startTimer() {
clickTimer = window.setTimeout(function(){
document.getElementById("scherm4").style.visibility = "visible";
document.getElementById("scherm2.2").style.visibility = "hidden";
},4000);
}
function stopTimer() {
window.clearTimeout(clickTimer);
}
function restartTimer() {
stopTimer();
startTimer();
}
document.getElementById("buttontimer").addEventListener("click", function(){
restartTimer();
});
This way when you want to stop the timer or start the timer, you have to just call above functions for other scenarios.
eg:
If you have an init function:
function init() {
...
//some code
startTimer();
}
And maybe call stop timer like so:
function clicks5times() {
...
stopTimer();
}
Split your event handlers in two different functions (eg firstClick and secondClick). The first handler should just add a second event listener and remove it after 4 seconds. For this one-off task, use setTimeout instead of setInterval as you need the task to be done only once after 4 seconds and not every 4 seconds. So I would proceed as follows:
var secondClick = function() {
// DO WHATEVER YOU WANT TO HAPPEN AFTER THE SECOND CLICK
}
var firstClick = function() {
// DO WHATEVER YOU WANT TO HAPPEN AFTER THE FIRST CLICK
document.getElementById("buttontimer").addEventListener("click", secondClick);
setTimeout(function() {
document.getElementById("buttontimer").removeEventListener("click", secondClick);
}, 4000);
};
buttonElement.addEventListener("click", firstClick);
in Javascript
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<button id="buttontimer">fghfgh</button>
</body>
</html><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<button id="buttontimer">fghfgh</button>
<script>
document.getElementById('buttontimer').onclick = function(){
document.getElementById("buttontimer").disabled=true;
setInterval(function(){
if (document.getElementById("buttontimer").disabled == true) {
document.getElementById("buttontimer").disabled = false;
}
},10000);
};
</script>
</body>
</html>
and Jquery
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var button = $('<button>Click Me</button>');
button.clicked = false;
$('body').append(button);
var clicked = false;
button.click(function(){
button.clicked = true;
button.prop('disabled', true);
clicked = true
setInterval(function(){
if (clicked) {
button.prop('disabled', false);
}
},10000);
});
});
</script>
</head>
<body>
</body>
</html>
once u click button disable the property after the timer finish enable back the property
I have the following button:
<input type="button" class ="anhalteButton" id="StopButton" value="▋ ▋"/>
which I want to execute the following function (viewsLoop is a global variable):
function clearTDLoop(){
clearInterval(viewsLoop);
}
If I call the function via the button's onclick attribute. i.e.:
onclick="clearTDLoop()" it works flawlessly.
However, I would like to call the function through a JS event listener, but that does not work at all. Do you guys have any idea what I might be doing wrong? My Event Listener Code is attached:
var stopButtonEl = document.getElementById("StopButton");
stopButtonEl.addEventListener("click",clearTDLoop);
Sry for the prior confusion, where my code example stated "StartButton" as the button ID, I copied the wrong ID, the problem persists..
It looks like you have the wrong ID for your event listener:
var startButtonEl = document.getElementById("StartButton");
startButtonEl.addEventListener("click",clearTDLoop);
Should be:
var stopButtonEl = document.getElementById("StopButton");
stopButtonEl.addEventListener("click",clearTDLoop);
I've set an example code for you, please check it:
var tdLoop;
var counter = 0;
var startButton = document.getElementById('startButton');
startButton.addEventListener('click', startTDLoop, false);
var stopButton = document.getElementById('stopButton');
stopButton.addEventListener('click', clearTDLoop, false);
var result = document.getElementById('result');
function startTDLoop() {
tdLoop = setInterval(updateValue, 1000);
}
function updateValue() {
counter++;
result.innerHTML = counter;
}
function clearTDLoop() {
counter = 0;
clearTimeout(tdLoop);
}
#result {
padding: 15px 0 0;
}
<input type="button" class ="anhalteButton" id="startButton" value="Start"/>
<input type="button" class ="anhalteButton" id="stopButton" value="Stop"/>
<div id="result"></div>
According to this thread: how many javascript setTimeout/ setInterval call can be set simultaneously in one page? it is possible to have multiple setIntervals at the sametime.
However, is it possible to have a setInterval and setTimeout at the sametime?
This is not working...
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
init();
});
function init() {
$('#startbutton').on('click', handleClick);
}
</script>
</head>
<body>
<script>
var playBeep = function () {
var snd = new Audio("beep-7.wav");
snd.play();
}
var handleClick = function () {
var interval1 = setInterval(updateDisplay, 1);
makeIntervals([1,2,3], playBeep);
}
var makeIntervals = function(timeList,callback){
intervals = []
for(i in timeList){
intervals.push(setTimeout(callback,timeList[i]))
}
return intervals
}
function updateDisplay() {
var value = parseInt($('#timer').find('.value').text(), 10);
value++;
$('#timer').find('.value').text(value);
}
</script>
<button type="button" id="startbutton">Play Beep</button>
<P>
<div id="timer"><span class="value">0</span> ms</div>
<P>
Of course. However just make sure you don't have too many.