Use JavaScript to change ownership in CSS

4

I'm not able to make it work, I have a retractile side menu and a button on a bar in the header. I set my menu to margin-left: -250px; and wanted it when I pressed the button it would go to margin-left: 0; , thus making the menu appear again.

Menu CSS:

#menu-lateral {
    width: 250px;
    height: 100%;
    margin-left: -250px;
}

Button HTML:

<div class="btn-header">
      <a href="" id="btn-menu">
      <img src="img/menu.png">
      <img src="img/icone.png">
      <p>Home</p></a>
</div> 

JavaScript I've done:

    var clique = document.getElementById("btn-menu"); 
    var menuLateral = document.getElementById("menu-lateral");

    clique.onclick = function(){
        document.menuLateral.style.marginLeft = "0";
    };

My goal is:

When you click the change button in #menu-lateral margin-left: -250px; to margin-left: 0; and when the menu is open, clicking it again will close it (set margin-left: -250px; again).

    
asked by anonymous 16.04.2015 / 21:18

1 answer

8

You have to change two things:

You must first use e.preventDefault(); to prevent the link from reloading the page, or to add # to href .

According to you declare a variable that points to the menu, var menuLateral = document.getElementById("menu-lateral"); . Later in code instead of using the variable you use document.menuLateral.style... when you should only use menuLateral.style...

Fixed looks like this:

clique.onclick = function (e) {
    e.preventDefault();
    menuLateral.style.marginLeft = "0";
};

Example (with CSS transition too): link

You can also do this via CSS class , in which case you apply the new style via CSS that is better. An example of how to do toggle would be:

CSS

.toggleMenu {
    margin-left: 0px !important;
}

JavaScript

clique.onclick = function (e) {
    e.preventDefault();
    menuLateral.classList.toggle('toggleMenu');
};

toggle adds a class and / or removes it if it already exists. It's like the button of the television command, it loads to on / off. The !important is to say that when this class is added then this rule overrides the other of margin-left: -250px; . The transition , says that the change must be by animation and duration of 0.7 seconds

jsFiddle: link

    
16.04.2015 / 21:28