This is a follow up from this post: @keeyh.mba/notes-from-qualtrics-js-series-basic-create-boxes-and-hiding-next-button
Qualtrics.SurveyEngine.addOnload(function() {
var w = 100; // width of the squares
var d = 350; // distance between the centers of the squares
// Create squares
var square1 = document.createElement('div');
square1.id = 'square1';
square1.style.width = w + 'px';
square1.style.height = w + 'px';
square1.style.background = 'red'; // Initially red
square1.style.position = 'absolute';
square1.style.left = (d/2) - (w/2) + 'px'; // Positioning from the center
var square2 = document.createElement('div');
square2.id = 'square2';
square2.style.width = w + 'px';
square2.style.height = w + 'px';
square2.style.background = 'grey'; // Initially grey
square2.style.position = 'absolute';
square2.style.left = (d/2) + (w/2) + d + 'px'; // Positioning from the center
// Append squares to the body of the question
this.getQuestionContainer().appendChild(square1);
this.getQuestionContainer().appendChild(square2);
// Hide next button
this.hideNextButton();
// Start timer
console.log("Timer started");
var start = new Date();
// Store start time in embedded data field
Qualtrics.SurveyEngine.setEmbeddedData('start_time', start.getTime());
// Event listeners for squares
square1.addEventListener('click', function() {
square1.style.background = 'grey'; // Change red to grey
square2.style.background = 'red'; // Change grey to red
});
square2.addEventListener('click', function() {
square2.style.background = 'grey'; // Change red to grey
square1.style.background = 'red'; // Change grey to red
});
});
As I wanted the color of the box to toggle when clicked, I had to use the Event Listener.
This is where it is changed.
square1.addEventListener('click', function() {
square1.style.background = 'grey'; // Change red to grey
square2.style.background = 'red'; // Change grey to red
});
Directly work with square1, and call the addEventListener which is 'listening' for click. Within it, let the function change the style background to what we want the two boxes to look like when square1 is clicked.
Repeat for square2, and of course reverse the colour there.