How to toggle an element from clicking a different element in JavaScript?

1981 views javascript
10

So I'm super new to JavaScript and web development in general but I'm trying to find a way to toggle an element by clicking on another element.

To clarify, this is for the mobile version of my site. This is what it looks like now: https://i.stack.imgur.com/F3lVo.png

What I'm trying to do is have the little hamburger menu in the bottom left corner be clicked to reveal my navigation bar which would slide in from the right.

If it makes the solution any different I am also using media queries to hide the navigation bar once the webpage becomes a certain width.

Here's what the JavaScript looks like for the hamburger menu so far:

<script>
    $( document ).ready(function() {
        var hamburger = $('#hamburger-icon');
        hamburger.click(function() {
        hamburger.toggleClass('active');
        return false;
        });
    });
</script>

And here's the CSS it activates:

#hamburger-icon.active .line-1 {
transform: translateY(10px) translateX(0) rotate(45deg);
-webkit-transform: translateY(10px) translateX(0) rotate(45deg);
-moz-transform: translateY(10px) translateX(0) rotate(45deg);
}

#hamburger-icon.active .line-2 {
opacity: 0;
}

#hamburger-icon.active .line-3 {
transform: translateY(-11px) translateX(0) rotate(-45deg);
-webkit-transform: translateY(-11px) translateX(0) rotate(-45deg);
-moz-transform: translateY(-11px) translateX(0) rotate(-45deg);
}

This animates the hamburger menu to become and X when clicked, but is there any way I can also have it trigger my navigation bar to become visible? Any help would be appreciated, thanks!

answered question

2 Answers

1

Yes, of course it can. Here's how you'd do it:

$( document ).ready(function() {
    var hamburger = $('#hamburger-icon');
    var navbar = $"#navbar"); //You'll have to edit this line, I'm just guessing
    hamburger.click(function() {
        hamburger.toggleClass('active');
        navbar.toggle();
    });
});

Note that you'll have to change the var navbar = $("#navbar"); as I don't know what your navbar is.

posted this
6

Maybe you could try like this:

$( document ).ready(function() {
  var hamburger = $('#hamburger-icon');
  hamburger.on('click', function(){
    hamburger.toggleClass('active');
  });
});

posted this

Have an answer?

JD

Please login first before posting an answer.