0

HTML :

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>About Us</title>
        <link rel="stylesheet" href="css/design.css">
        <script src="js/script.js"></script>
    </head>
    <body>
        <div id="static">
            <input type="image" src="media/tag.png" id="tag"/>
            <div id="mobile-nav-bar">
                <button value="overview" class="bar-element">Overview</button><br><br><br>
                <button value="what_we_do" class="bar-element">What We Do</button><br><br><br>
                <button value="innovations" class="bar-element">Innovations</button><br><br><br>
                <button value="why_choose_us" class="bar-element">Why Choose Us</button><br><br><br>
                <button value="team" class="bar-element">The Team</button><br><br><br>
                <button value="contact" class="bar-element">Contact Us</button>
            </div>

        </div>
    </div>
</body>

CSS:

#mobile-nav-bar {
    width: 20vw;
    height: 50vh;
    position: relative;
    top: 15vh;
    left: 40vw;
    display: block;
    animation-name: navbarOut;
    animation-duration: 0.5s;
    animation-fill-mode: forwards;
    animation-play-state: running;
}

@keyframes navbarOut {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}

JS:

document.addEventListener("DOMContentLoaded", () => {

    const bar = document.querySelector("#mobile-nav-bar");
    const content = document.querySelector("#content");


    document.querySelector("#tag").onclick = () => {
        console.log(bar.style);
    }
});

I am trying to access style properties of mobile-nav-bar but every time the dictionary returned has empty values. I am trying to use the style property of display but unable to do so since it is empty. Whereas I have defined the CSS property. I am new to this please help.

I'm TreaSUre
  • 102
  • 5

2 Answers2

1

element.style only works for inline styles, while your navbar's style is defined elsewhere (separate file/style tag)

Instead, you should use getComputedStyle.

document.addEventListener("DOMContentLoaded", () => {

    const bar = document.querySelector("#mobile-nav-bar");
    const content = document.querySelector("#content");


    document.querySelector("#tag").onclick = () => {
        console.log(window.getComputedStyle(bar).getPropertyValue("display"));
        // prints "block"
    }
});

More information: Get a CSS value with JavaScript

jdabtieu
  • 534
  • 5
  • 20
0
document.addEventListener("DOMContentLoaded", () => {

    const bar = document.querySelector("#mobile-nav-bar");
    const content = document.querySelector("#content");

    document.querySelector("#tag").onclick = () => {
        console.log(window.getComputedStyle(bar).getPropertyValue("display"));
        // prints "block"
    }
});
marko-36
  • 1,309
  • 3
  • 23
  • 38