简体   繁体   中英

How to change current background color of button onclick jQuery

I work with quiz, and i want to change colors of buttons, so when i tap on the button i want to change his background color, i have div in which i have dynamycaly created button, and for this button i wants to change color.

JS:

var quiz = [
    { stepName: "Check Oil", frequency: "1 / Shift", stepDescription: "Verify the presence of spilled oil", image: "https://cdn.iconscout.com/icon/free/png-512/schedule-maintenance-1575170-1331504.png", choices: ["OK", "NOK", "N/A"], savedAnswer: "" },
    { stepName: "Check noise", frequency: "1 / Shift", stepDescription: "Check for unusual noise from machine", image: "", choices: ["OK", "NOK", "N/A"], savedAnswer: "" },
    { stepName: "Clean filter", frequency: "1 / Week (Monday)", stepDescription: "Clean the air filter at compressed air inlet", image: "https://cdn.iconscout.com/icon/free/png-512/schedule-maintenance-1575170-1331504.png", choices: ["OK", "NOK", "N/A"], savedAnswer: "" },
    { stepName: "Check Andon", frequency: "1 / Shift", stepDescription: "Check if andon light is on", image: "https://cdn.iconscout.com/icon/free/png-512/schedule-maintenance-1575170-1331504.png", choices: ["OK", "NOK", "N/A"], savedAnswer: "" },
    { stepName: "Safety barrier", frequency: "1 / Shift", stepDescription: "Check the proper functionality of light barrier(s)", image: "https://cdn.iconscout.com/icon/free/png-512/schedule-maintenance-1575170-1331504.png", choices: ["OK", "NOK"], savedAnswer: "" }
];

var index = 0;

function parseQuiz() {
    for (var i = 0; quiz.length > i; i++) {
        creatingAnswers(quiz[index].choices[i]);
        setQuizToDiv(quiz[index].stepName, quiz[index].frequency, quiz[index].stepDescription, quiz[index].image);
    }
}

function setQuizToDiv(stepName, frequency, stepDescription, image) {
    $(".quiz-container").html('');
    var quizHtml;
    if (image != "") {
        quizHtml = `
        <div class="step-name">
            ${stepName}
        </div>
        <div class="frequency">
           Frequency: ${frequency}
        </div>
        <div class="step-desc">
           ${stepDescription}
        </div>
        <div class="step-image">
        <div id="overlay"></div>
        <img class="main-img" src="${image}" />
        </div>`;
    } else {
        quizHtml = `
        <div class="step-name">
            ${stepName}
        </div>
        <div class="frequency">
           Frequency: ${frequency}
        </div>
        <div class="step-desc">
           ${stepDescription}
        </div>
        <div class="separation-div"></div>
        `;
    }

    $(".quiz-container").append(quizHtml);
}

function creatingAnswers(choises) {
    if (choises != undefined) {
        var answers = `<button class="btn next-btn">${choises}</button>`
        $(".answ-container").append(answers);
    }
}

parseQuiz();

$(".quiz-container").on("click", ".main-img", function () {
    $('#overlay')
        .css({ backgroundImage: `url(${this.src})` })
        .addClass('open')
        .one('click', function () { $(this).removeClass('open'); });
});

$(".answ-container").on("click", ".next-btn", function () {
    let indexData = index + 1;
    let arrayData = quiz.length - 1;
    if (indexData <= arrayData) {
        quiz[index].savedAnswer = $(this).text();
        index++;
        $(".answ-container").html("");
        parseQuiz();
        navButton();
    }
});

HTML:

<div class="quiz-container"></div>
<div class="answ-container"></div>

So i try to change bg color in this func

$(".answ-container").on("click", ".next-btn", function () {

To add this code:

$(this).css("background-color","red")

But this is not working for me. So on the click i want to change bg of button, and when i go to the nex question previus button which i colored is saved.

Working example: https://jsfiddle.net/qunzorez/Lnt8f2dv/8/

OK I think I understood what you wanted. Here is a clue so that you can progress. I won't edit you jsfiddle because your code is very messy...

What you can put in your JS:

$(".answ-container").on("click", ".next-btn", function () {
  // adding the class to the clicked button
    $(this).addClass('clicked')
  // removing the class of the siblings
  $(this).siblings().removeClass('clicked')
  // saving the index of the answer clicked
  quiz[index].savedAnswer = $(this).index()

What you can put in your CSS:

.clicked {
  background-color: green;
}

And when you create the answer buttons, you add the "clicked" class for the button with the index saved.

The principle is to play with the classes.

if I answer in first question OK, and I go to next one, but I make mistake in prev question I will have possibility to change mind, for this I create button previus[sic], when user tap on prev, it's going to prev question and should show previus[sic] answer

In creatingAnswers check against savedAnswer for the current question

if (quiz[index].savedAnswer == choises)

and do your thing (eg add a class) - in the updated fiddle (below) I've swapped around the append to appendTo to get the jquery obj being added, giving:

function creatingAnswers(choises) {
    if (choises != undefined) {
        var answers = `<button class="btn next-btn">${choises}</button>`
        var ans = $(answers).appendTo(".answ-container");
        if (quiz[index].savedAnswer == choises) {
            ans.addClass("userchoice");
        }
    }
}

Updated fiddle: https://jsfiddle.net/187autjo/


There's also an earlier bug (discussed in the comments) which loops the quiz count instead of the answer count - this is also updated in the fiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM