Search code examples
javascriptjqueryincrementaddeventlistenerevent-listener

Increase and Decrease of count


I'm trying to create a code that can increase and decrease via clcik of a button html code but the problem is i cant get it to function I've tried different options.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="styles.css">
    <title>Document</title>
</head>

<body>
    <div id="body">
        <h1>COUNTER</h1>
        <span id="time">0</span><br>
        <button id="lower"  onclick="reduceone()" type="button">LOWER COUNT</button><BR>
        <button id="add" onclick="addone()" type="button">ADD COUNT</button>
    </div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="index.js"></script>
</body>
</html>

javascript code:

$("#add").click(function (){
    let count = 0;
    count ++;
    $("#time").text(count);
});

$(#lower).click(function(){
    let count = 0;
    count --;
    $("#time").text(count)
});

Solution

  • You need to share the state between two functions so each of them could see the shared state that they are changing.

    Also, all id or class names should be between inverted commas like that "#lower"

    let count = 0; // Shared state that both functions can see
    
    $("#add").click(function (){
        count++;
        $("#time").text(count);
    });
    
    $("#lower").click(function(){ // "#lower" not #lower
        count--;
        $("#time").text(count)
    });