I'm just getting started with frontend development. I tried to make a pretty barebones cookie consent notice. I still don't fully understand flexbox and positioning, so the code is messy.
HTML:
<button id="shownotice">Click to ask</button>
<div id="consent_elem" class="consent_notice" hidden="true">
<p>Are you fine with cookies?</p>
<div id="buttons">
<button class="consent_button" id="yes">Yes</button>
<button class="consent_button" id="no">No</button>
</div>
CSS:
#shownotice {
background-color: cyan;
border:0;
padding: 5px;
}
[hidden] { display: none !important; }
.consent_notice {
display: flex;
align-items: center;
justify-content: space-between;
position: fixed;
background-color: red;
bottom:0px;
left: 0px;
right: 0px;
overflow: auto;
}
#buttons {
display: flex;
margin-right: 10px;
flex-direction: column;
padding: 5px;
}
.consent_button {
margin: 5px;
background-color: gray;
border: 0;
padding: 3px;
}
JS:
show_button = document.querySelector("#shownotice");
consent_elem = document.getElementById("consent_elem");
show_button.onclick = (e) => {
consent_elem.hidden = consent_elem.hidden ? false : true;
}
1 Answer 1
IDs
Avoid IDs for styling. It's ok to use them to identify elements with JavaScript, but the specificity in CSS can make structuring the styles tricky.
Names such as buttons
, yes
and no
are very generic, that could easily be needed more than once in a document.
Also try to be more consistant with the style of classes/names/IDs. For example, shownotice
has no underline, but consent_notice
does. Consider using hyphens instead of an underlines in order to match the general style of CSS, which uses hyphens, as in background-color
.
HTML
"true"
is not a valid value for the attribute for the attribute hidden
. As a boolean attribute hidden
is either present without a value (or, if you prefer use the value "hidden"
as in hidden="hidden"
) or not present. hidden="false"
, for example, would still hide the element.
JavaScript
Declare your variables with const
or let
(or var
if you need to support very old browsers).
In JavaScript it is convention to write variable names in camelCase and not with underlines.
You could be more consistent when retrieving elements by ID and use either querySelector
or getElementById
, but not both.
Don't use on...
properties to assign event handlers. Use addEventListener
.
Use the boolean negator !
to toggle boolean values:
consent_elem.hidden = !consent_elem.hidden;