Trigger javascript function after clicking on two buttons

I am currently working on developing a web game inspired by Duolingo. In a specific scenario, I need a function to be triggered after two button clicks to progress further. However, I am facing challenges in finding solutions online or understanding it on my own since this is my first time working with JavaScript.

For scenarios with a single answer, I have successfully implemented the following function which is executed after a single button press:

function answer (URL) {
    setTimeout( function() { window.location = URL }, 3500 );
    document.getElementById("answerDisplay").style.display = "inline";
    document.getElementById("buttonCorrectAnswer").style.display = "none";
    document.getElementById('video').play();
  }

I have attempted to address the issue by checking if "answerDisplayOne" and "answerDisplayTwo" are both visible and then calling a function, but have not been successful:

function answerOne() {
  document.getElementById("answerDisplyOne").style.display = "inline";
  document.getElementById("buttonCorrectAnswerOne").style.display = "none";
}

function answerTwo() {
  document.getElementById("answerDisplayTwo").style.display = "inline";
  document.getElementById("buttonCorrectAnswerTwo").style.display = "none";
}


if ( $("#answerDisplayOne").css('display') == 'inline' && $("#answerDisplayTwo").css('display') == 'inline'){
  function delayTwo (URL) {
    setTimeout( function() { window.location = URL }, 3500 );
    document.getElementById('video').play();
  }
}

Answer №1

To find a solution, I attempted to check if both "answerDisplayOne" and "answerDisplayTwo" are visible before calling a function, but without success:

The issue lies in only checking the condition once:

if ( $("#answerDisplayOne").css('display') == 'inline' && $("#answerDisplayTwo").css('display') == 'inline'){
  function delayTwo (URL) {
    setTimeout( function() { window.location = URL }, 3500 );
    document.getElementById('video').play();
  }
}

This code checks the condition and defines the function delayTwo IF both #answerDisplayOne and #answerDisplayTwo have their css property "display" set to "inline". This is not the desired behavior.

What is needed is to check the condition each time the user presses a button:

function answerOne() {
  document.getElementById("answerDisplyOne").style.display = "inline";
  document.getElementById("buttonCorrectAnswerOne").style.display = "none";
  check();
}

function answerTwo() {
  document.getElementById("answerDisplayTwo").style.display = "inline";
  document.getElementById("buttonCorrectAnswerTwo").style.display = "none";
  check();
}

function check() {
  if ($("#answerDisplayOne").css('display') == 'inline' && $("#answerDisplayTwo").css('display') == 'inline'){
    setTimeout( function() { window.location = URL }, 3500 );
    document.getElementById('video').play();
  }
}

¹ By "once" I mean literally only once. JavaScript executes sequentially from top to bottom. This is why event listeners are used to trigger code when a specific event occurs. We cannot predict in advance when the user will click a button, can we?

Answer №2

To activate a third event based on two independent events, you must constantly monitor both events and keep track of their history. Whenever one of the events occurs, you need to check if the other event has occurred before and, if so, trigger the third event. If not, you need to retain the knowledge of the event that has occurred until the other event is detected. (Understanding this concept might be clear, but the implementation in javascript could be challenging).

Below is a practical example where two red boxes are displayed. When either box is clicked, it changes its color, but the third box remains unchanged until both boxes are clicked. The sequence in which the boxes are clicked does not matter. In this instance, the 'memory' of previous clicks is maintained by verifying if the other box has already been clicked.

Essentially, this example demonstrates how to establish event listeners to continuously monitor changes. These listeners are functions assigned to page elements that require two parameters: 1) the event to monitor, such as click' but it could also be change or mouseover, and 2) the action to perform when the event is detected. Typically, as shown in this example, an arrow or lambda function can be utilized as the actual argument, but referencing an external function would work as well.

// References to page objects:
const firstTarget = document.getElementById('target1');
const secondTarget = document.getElementById('target2');
const output = document.getElementById('output');

// Event listener for click on first target:
firstTarget.addEventListener('click', event => {
event.target.style="background:yellow";
event.target.innerHTML="1st clicked";
checkStatus();
}); // End of event listener 1;

// Event listener for click on second target:
secondTarget.addEventListener('click', event => {
event.target.style="background:green";
event.target.innerHTML="2nd clicked";
checkStatus();
}); // End of event listener 2;

function checkStatus() {
  if (firstTarget.innerHTML=="1st clicked" && secondTarget.innerHTML=="2nd clicked") {
   output.innerHTML = "BOTH CLICKED!";
   output.style="background:red";
   } // End of if block;
} // End of checkStatus function;
div {
 display: inline-block;
 background: red;
 width: 80px;
 height: 30px;
 border: 1px solid black;
 padding: 10px;
 margin: 5px;
}
#output {
 background: white;
 width: 195px;
 height: 35px;
}
<div id="target1">click me</div>
<div id="target2">click me</div>
<br>
<div id="output"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display a new div with its content every 5th item

I am currently working with a Smarty template that contains the following code output: Check out my other question on Stackoverflow My problem lies in the fact that the provided code does not repeat the inserted HTML after every 5 elements... Could some ...

Empty space encompassing the entire sheet

While developing my website, everything seemed normal until I added a CSS document to my HTML page. Now, when we open the website , there is a white space around the entire page. I attempted to set the body class to container-fluid since I am using Bootst ...

Error message encountered when submitting a form after receiving an AJAX response: VerifyCsrfToken Exception

I'm encountering an issue with my AJAX functionality that involves rendering a form with multiple input fields and a submit button. Here is the AJAX call: <script type="text/javascript"> $('#call_filter').click(function() { $.aja ...

How should HTML5 type "month" be stored in a Django model's database using which data type?

My HTML form includes a field for inputting a month <input type='month' name="last_appraisal" id='txtLastAppraisal' value='2013-12' /> In the Django model, I have defined this field as last_appraisal = models.DateFie ...

Is there a way to overlay a 'secret' grid on top of a canvas that features a background image?

I am currently working on developing an HTML/JS turn-based game, where I have implemented a canvas element using JavaScript. The canvas has a repeated background image to resemble a 10x10 squared board. However, I want to overlay a grid on top of it so tha ...

What is the best way to align a scalable SVG image in the center?

My goal is to horizontally align this SVG within its container, which could be any div, body, or other element. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1250 190" preserveAspectRatio="xMidYMid slice" class="svg-content"> &l ...

Is it possible to pass a class method to an onClick event from within the render method in ReactJS?

Excuse my lack of experience, but I haven't been able to find a solution to this yet. I am attempting to utilize a class method as a callback for the onClick event in my JSX. Below is the code for my App component: import React from 'react&apo ...

What is causing the .responseToString function to be recognized as not a function?

Consider the following scenario with Typescript: interface IResponse { responseToString(): string; } export default IResponse; We have two classes that implement this interface, namely RestResponse and HTMLResponse: import IResponse from "./IRespo ...

Guide to sending post variables in an AngularJS service

Is there a way to send POST variables to a RESTful API using an angularjs service? I currently have the following setup: angularjsServices.factory('LoginService', [ '$resource', function($resource){ return function(user, pass){ ...

Resizing a floated div causes the image to break out

My webpage has a container div with two floated left divs inside, positioned side by side. The right div contains a YouTube video and an image. However, when I resize the page, the video and picture flow out of the containing floated div instead of dropp ...

The integration of RxJS into a Master/Worker workflow

My current program utilizing the cluster library is structured like this: if(cluster.isMaster) { // include Rx subscriptions and workflows for the Master here } else if (cluster.isWorker){ // include Rx subscriptions and workflows for a Worker here } ...

Prevent removal of h2 tag within a contenteditable segment

Can a section be made permanent within a contenteditable element to prevent user removal? I have an h2 tag inside a contentEditable div. I do not want the user to be able to edit the h2 tag, so I set contentEditable=false, but they can still select and de ...

What is the best way to incorporate CSS into an Angular 4 project?

I'm struggling to figure out how to import CSS into my app component. All the information I find on Google seems to lead me in different directions... Within my component, I have defined: @Component({ styleUrls: ['../css/bootstrap.min.css&ap ...

What is the best way to create a non-reactive value in Vue.js?

In my Vue.js app, I am facing an issue where an array value is becoming reactive even though I want it to remain un-reactive. The array should only be updated when a specific "refresh" action is completed. However, every time a new value is assigned to the ...

Troubleshooting: Unable to Sort Column in ngx-DataTable Angular 4

As a newcomer to Angular, I have been encountering some challenges while using ngx-DataTable. I am currently utilizing a simple ngx-DataTable for basic operations. The issue I am facing is that the sorting functionality is not working on a specific column, ...

Having trouble deploying my Express/Next app on Netlify

I am facing issues deploying my Next/Express app on Netlify. While the app functions perfectly locally, I encounter problems when attempting to deploy it using Netlify lambda function. Here are the links to my test git repositories: https://github.com/La ...

None of the Views are rendered after executing RedirectToAction

I created a Login Page that redirects to the required page after validation. However, when it redirects, the previous Login page view appears instead of the expected view. Below is the JavaScript code I am using: function abc() { var email = ...

Issue with a stationary directional light tracking the movement of a rotating object and/or changes in the camera perspective

I've been facing a challenge in implementing a day-night cycle with a directional light in an Earth model using custom shaders. Everything seems to work fine with the night and day maps, as well as the light, as long as I don't manipulate the cam ...

Google Maps is experiencing difficulties maintaining its longitude and latitude coordinates within the Bootstrap tabbed user interface

I implemented ACF's Google Map to display a map on my webpage. I followed the instructions closely and made some minor modifications to the map js for styling purposes. One key change I had to make was in this section to ensure the map loads correctly ...

Submitting the form with a target of _blank will result in the form being submitted on both a

I am currently working on a form that includes both a "Submit" button and a "Preview" button. While the submit button is functioning correctly, I am experiencing an issue with the Preview button. When clicked, it opens up a new page with the preview as in ...