How do I add two functions using javascript?

97 Views Asked by At

I'm creating a choose your own adventure game that uses a health bar and changing texts. My health bar is able to change with my current code but the text does not. Is there something I am missing? What can I do? The two buttons are identified with "btn q1" and it reads "Question1", and "btn q2" and it reads "Question2". I would like to change "Question1" to "Question1A", etc. Here is my html for the buttons:

<div class="click">
    <span class="btn q1" id="btn q1" onclick="remove(); change();">
        Question1
    </span>
    <span class="btn q2" id="btn q2" onclick="remove(); change();">
        Question2
    </span>
</div>;

And my javascript:

var _Health = 100;

function remove() {
    let addHealth = document.getElementById("health");
    _Health += 20;

    if (addHealth) {
        addHealth.style.width = _Health + "%";
        addHealth.innerHTML = _Health + "ep";
    }
}

function remove() {
    let damage = document.getElementById("health");
    _Health -= 10;

    if (damage) {
        damage.style.width = _Health + "%";
        damage.innerHTML = _Health + "ep";
    }
}

function change() {
    var elem = document.getElementById("btn q1");
    if ((elem.value = "Question1")) elem.value = "Question1A";
    else elem.value = "Question1B";
}
function change() {
    var elem = document.getElementById("btn q2");
    if (elem.value == "Question2") elem.value = "Question2A";
    else elem.value = "Question2B";
}

1

There are 1 best solutions below

0
Giacomo Brunetta On

You can’t create functions with same name. You should create remove1() and remove2() for example, and call them into the button. But it is not the right way: you need to generalise the functions. Consider the example of Manuel in the comment: it is enough to pass the parameter with the name of the button, and execute all the stuffs with the name passed.

<span class="btn_q1" id="btn_q1" onclick= "remove(10); change(“btn_q1”, “Question1A”);">Question1</span>
            <span class="btn_q2" id="btn_q2" onclick= "remove(20); change(“btn_q2”,”Question1B”);">Question2</span>
        </div> 

And In the js:

    function change(btn,value)
{
    var elem = document.getElementById(btn);   
elem.value = value;
    }

    function remove(n) {
    let addHealth = document.getElementById('health')
    _Health += n;

    if (addHealth) {
        addHealth.style.width = _Health + '%'; 
        addHealth.innerHTML = _Health + 'ep';
    }
}

Last thing: don’t use namespaces in the ids. Use underscore instead of space (same in classes)