Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my copy button disappear when I click another button?

I am relatively new to programming and am trying to program a calculator. I tried to make a copy button to copy the result of the calculation. However, when I click another button, like a number, the copy button disappears.

const display = document.getElementById("display");
const calculation = document.getElementById("calculation");
const buttons = document.querySelectorAll(".btn");
const copyButton = document.getElementById("copy");

let calcString = "";
let result = null;

buttons.forEach((button) => {
    button.addEventListener("click", () => {
        const value = button.dataset.value;

        if (button.classList.contains("clear")) {
            calcString = "";
            display.textContent = "0";
            calculation.textContent = "0";
            result = null;
        } else if (button.classList.contains("equals")) {

            try {
                result = eval(calcString);
                display.textContent = result;
                calculation.textContent = `${calcString} =`;
                calcString = result.toString();
            } catch (error) {
                display.textContent = "Error";
                calculation.textContent = "Invalid Input";
                calcString = "";
                result = null;
            }
        } else {

            calcString += value;
            calculation.textContent = calcString;
            display.textContent = value;
        }
    });
});

copyButton.addEventListener("click", () => {
    if (result !== null && result !== "Error") {
        navigator.clipboard.writeText(result)
            .then(() => {
                alert("Result copied to clipboard");
            })
            .catch((err) => {
                console.error("Error copying to clipboard: ", err);
            });
    } else {
        alert("Nothing to copy");
    }
});
<head>
    <meta charset="UTF-8">
    <title>Calculator</title>
    <link rel="stylesheet" href="styles.css">
    <script src="main.js"></script>
</head>
<body>
<div class="calculator">
    <div class="calculation" id="calculation">
        <h1 class="calculation-text">0</h1>
        <button class="copy" id="copy">Copy</button>
    </div>
    <div class="display" id="display">0</div>
    <div class="buttons">
        <button class="btn" data-value="7">7</button>
        <button class="btn" data-value="8">8</button>
        <button class="btn" data-value="9">9</button>
        <button class="btn operator" data-value="/">÷</button>

        <button class="btn" data-value="4">4</button>
        <button class="btn" data-value="5">5</button>
        <button class="btn" data-value="6">6</button>
        <button class="btn operator" data-value="*">×</button>

        <button class="btn" data-value="1">1</button>
        <button class="btn" data-value="2">2</button>
        <button class="btn" data-value="3">3</button>
        <button class="btn operator" data-value="-">−</button>

        <button class="btn" data-value="0">0</button>
        <button class="btn" data-value=".">.</button>
        <button class="btn clear" id="clear">C</button>
        <button class="btn operator" data-value="+">+</button>

        <button class="btn equals" id="equals">=</button>
    </div>
</div>
</body>

I want the copy button to be next to the result, however to fix this problem I have to move the copy button to be outside of the result div:

<button class="copy" id="copy">Copy</button>
<div class="calculator">
    <div class="calculation" id="calculation">
        <h1 class="calculation-text">0</h1>
    </div>

Can anyone help me fix this problem?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue you’re experiencing arises because your JavaScript code replaces the content of the calculation div, which contains both the result (h1 element) and the copy button. When you update the content of calculation, the button is removed.

Fix
To resolve this, modify your approach so the copy button remains in the DOM and doesn’t get overwritten. You can achieve this by restructuring the HTML and ensuring your JavaScript only updates the content of the result text without affecting the button.

Here’s how you can fix it:

<div class="calculation" id="calculation">
    <h1 class="calculation-text" id="result">0</h1>
    <button class="copy" id="copy">Copy</button>
</div>

Updated JS
Update your JavaScript to target only the text inside the h1 element instead of replacing the entire calculation div.

const display = document.getElementById("display");
const calculation = document.getElementById("calculation");
const resultText = document.getElementById("result");
const buttons = document.querySelectorAll(".btn");
const copyButton = document.getElementById("copy");

let calcString = "";
let result = null;

buttons.forEach((button) => {
    button.addEventListener("click", () => {
        const value = button.dataset.value;

        if (button.classList.contains("clear")) {
            calcString = "";
            display.textContent = "0";
            resultText.textContent = "0";
            result = null;
        } else if (button.classList.contains("equals")) {
            try {
                result = eval(calcString);
                display.textContent = result;
                resultText.textContent = `${calcString} = ${result}`;
                calcString = result.toString();
            } catch (error) {
                display.textContent = "Error";
                resultText.textContent = "Invalid Input";
                calcString = "";
                result = null;
            }
        } else {
            calcString += value;
            resultText.textContent = calcString;
            display.textContent = value;
        }
    });
});

copyButton.addEventListener("click", () => {
    if (result !== null && result !== "Error") {
        navigator.clipboard.writeText(result)
            .then(() => {
                alert("Result copied to clipboard");
            })
            .catch((err) => {
                console.error("Error copying to clipboard: ", err);
            });
    } else {
        alert("Nothing to copy");
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading