Home > Software design >  I cannot change the display on a class in javascript
I cannot change the display on a class in javascript

Time:06-05

I'm trying to change visibility of an element in JavaScript.

I tried running openloginHud(); with the console window and it responded with undefined

I have also tried using console and that told me the error was

Uncaught TypeError: Cannot read properties of null (reading 'style') at openloginHud (index.js:20:40) at HTMLInputElement.onclick (index.html:13:110)

My code

HTML:

<div ><input id="login" type="submit" name="login" onclick="openloginHud();" value="Login"/></div>
<div >
        <div >
            <h1>Login</h1>
            <div ><input type="email" name="email" id="email" placeholder="Email"></div>
            <div ><input type="password" name="password" id="pass" placeholder="Password"></div>
            <div ><input id="submit" type="submit" name="Login" onclick="login();" value="Login"/></div>
        </div>
    </div>

JavaScript:

function openloginHud() {
    document.getElementById("loginHud").style.display = "block";
}

Css:

.inputs {
    background-color: rgb(94, 94, 94);
    position: absolute;
    display: none;
    left: 50%;
    top: 40%;
    transform: translate(-50%, -50%);
    padding: 0 100px;
    padding-top: 50px;
    padding-bottom: 100px;
    border-radius: 55px;
}

.inputs .email {
    padding-bottom: 15px;
}

.inputs .email input,
.inputs .password input {
    padding: 10px;
    background: none;
    outline: none;
    border: 5px solid white;
    border-radius: 15px;
    color: white;
}

.inputs .email input::placeholder,
.inputs .password input::placeholder {
    color: rgb(199, 199, 199);
}

.inputs h1 {
    color: white;
    font-size: 65px;
    text-align: center;
}

.inputs .password input,
.inputs .email input {
    height: 20px;
    width: 250px;
}

CodePudding user response:

loginHud is a class, not an ID. You have 2 options:

If there is only one element with that class, just change it to an ID:

<div id="loginHud">

If there are more than one elements, use getElementsByClassName and loop through it:

for (let el of document.getElementsByClassName('loginHud')) {
    el.style.display = 'block';
}

CodePudding user response:

Change "document.getElementbyID" to

function openloginHud() {
    document.querySelector(".loginHud").style.display = "block";
}

querySelector allows you to use css Selectors like "#" and ".". It makes it easier to switch between the two types seamlessly. Just remember to use the CSS Selector, and it will change the style.

  • Related