Issue
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 class="pro-saved-team-btn" 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?
Solution
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"
Answered By - A Haworth
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.