Home > Blockchain >  HTML onclick button takes two clicks
HTML onclick button takes two clicks

Time:12-19

I saw the answers from similar questions but they did not help me

I have a button that when clicked, will change the background color of the button and hide/show some content

HTML

<button  id="{{ teams[loop.index0] | replace(' ', '')   'button' }}"
                            onclick="show_team('{{ team | replace(' ', '') }}', '{{ team | replace(' ', '')   'button' }}')">
                        {{ team.title() }}
</button>

JS in HTML

<script>
        function show_team(team, team_btn) {
            x = document.getElementById(team);
            btn = document.getElementById(team_btn);
            if (x.style.display === "none") {
                x.style.display = "block";
                btn.style.backgroundColor = '#1DA1F2';
            } else {
                x.style.display = "none";
                btn.style.backgroundColor = '#161616';
            }
        }
    </script>

I know the function works but I need to click on the button twice for the background color to change.

Anyone know how to fix this so it works after only one click?

CodePudding user response:

The problem is that when things start up noone has set the style of property display.

Hence the first time round the test x.style.display === "none" fails.

So then the code goes to set x.style.display to 'none'.

So the next time round the test wprks.

To avoid having to set every style display to none at the start change

x.style.display === "none"

to:

x.style.display != "block"

CodePudding user response:

The problem does not reproduce with the code snippet you've given:

<html>
<html>
<head>
</head>
<body>
<div id="teamId"> hee hee hee </div>
<button  id="buttonId" onclick="show_team('teamId','buttonId')">
 click
</button>
<script>
        function show_team(team, team_btn) {
            x = document.getElementById(team);
            btn = document.getElementById(team_btn);
            if (x.style.display === "none") {
                x.style.display = "block";
                btn.style.backgroundColor = '#1DA1F2';
            } else {
                x.style.display = "none";
                btn.style.backgroundColor = '#161616';
            }
        }
    </script>
</body>
</html>

You can do the following:

  1. add logs (console.log('clicked')) to your function so you are sure that every click you make is received by the button - and investigate the source of interceptions if some clicks never made it to button
  2. find whether there are some other places in your code that do something with these button and team IDs
  3. remove class pro-saved-team-btn from the button and check whether it changes button onclick behavior
  • Related