Search code examples
javascripthtmlbuttongoogle-chrome-extensiongetelementbyid

How to get my button to work using javascript?


I am creating an Google chrome extension and I am trying to get my stop/stop logging button to work within my function named Logger. When the button is pressed it doesn't react to the function I wrote, Currently it is displaying the stop-button but I want it to display the start-button when clicked. I hope I explained that to some understanding but do anyone possibly know why my function is not working?

Below is my current javascript function and html :

popup.js

//attempt to get start/stop logging buttons to work
function Logger(isLogging, notLogging) {
    if (isLogging = true, notLogging = false) {
        addRow();
        document.getElementById("click-start").style.display = "block";
        document.getElementById("click-stop").style.display = "none";    

    }
    if (isLogging = false, notLogging = true) {
        document.getElementById("click-start").style.display= "none";
        document.getElementById("click-stop").style.display= "block";
    }
}

//button to start logging
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("click-start").addEventListener("click", Logger(true, false));


});

//button to stop logging
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("click-stop").addEventListener("click", Logger(false, true));


});

popup.html

<!--Start button of logging-->
    <button class="button button1" id="click-start" >
    <u> Start Logging </u>
    </button>
    
    <!--Stop button of logging-->
    <button class="button button2" id="click-stop" >
    <u> Stop Logging </u>
    </button>

Image of current output--button currently doesnt react


Solution

  • This may help to get the core functionality working, this implementation can be much improved

    const btnStart = document.getElementById("click-start");
    const btnStop = document.getElementById("click-stop");
    
    //attempt to get start/stop logging buttons to work
    function Logger(isLogging) {
        console.log(isLogging)
        if (isLogging) {
            btnStart.style.display = "block";
            btnStop.style.display = "none";
        }else{
            btnStart.style.display = "none";
            btnStop.style.display = "block";
        }
    }
    
    //button to start logging
    document.addEventListener("DOMContentLoaded", function () {
        btnStart.addEventListener("click", function() {Logger(false)}); 
        btnStop.addEventListener("click", function() {Logger(true)});
    });
    

    You have to try to keep the queries to the DOM to a minimum. Have a look at the toggle method it will help to make your code a bit leaner and easier to maintain