Manuel Pepe Manuel Pepe - 3 months ago 14
CSS Question

Moving div back and forth with a button

I'm having a problem i can't see while making a div go left and right with the

.animate
of JQuery. I'm new to this web development so i ask for your kind help.

This are the files:



$(document).ready(function() {
$('#nav-button').click(function() {
$(this).data('clicked', true);
});
if ($('#nav-button').data('clicked')) {
$('#nav-menu').animate({
left: '200'
}, 500);
} else {
$('#nav-menu').animate({
left: '0'
}, 500);
}
});

html {
position: relative;
height: 100%;
background-color: #6E6E6E;
}
#container {} .nav-button {
position: absolute;
margin-top: -2px;
margin-left: 7px;
width: 32px;
height: auto;
z-index: 1;
}
.nav-menu {
background-color: #424242;
position: absolute;
top: 0px;
left: 0px;
width: 200px;
height: 100%;
}
.logo {
position: relative;
top: 250px;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 225px;
}
.logo h3,
h1 {
text-align: center;
font-family: Sansita One;
color: #222;
text-shadow: 0px 2px 3px #555;
}
.logo h1 {
margin-bottom: 3px;
}
.logo h3 {
margin-top: 2px;
}
.hover-rotate:hover {
-ms-transform: rotate(-170deg);
-webkit-transform: rotate(-170deg);
-moz-transform: rotate(-170deg);
-o-transform: rotate(-170deg);
transform: rotate(-170deg);
}

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js?ver=1.4.2'></script>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Sansita+One" />
<link href="main.css" rel="stylesheet" type="text/css" />
<script src="script.js" type="text/javascript"></script>
<title>Manuel Pepe - Test</title>
</head>

<body>
<div id="nav-bar" class="nav-bar">
<div id="container">
<img id="nav-button" class="nav-button" src="imgs/menu.png" />
<div id="nav-menu" class="nav-menu">
</div>
</div>
</div>
<div class="front-page">
<div class="logo">
<h1>Manuel Pepe</h1>
<h3>Test</h3>
</div>
</div>




Answer

Try this instead:

$(document).ready(function(){
    var $navButton = $('#nav-button'),
        $navMenu = $('#nav-menu'),
        transitioning = false;

    $navButton.click(function(){
        var $this = $(this);
        $this.data('clicked', !$this.data('clicked'));

        if(!transitioning) {
           transitioning = true;
           if($navButton.data('clicked')) {
             $navMenu.animate({left: '200'}, 500, function(){
                 transitioning = false;
             });
           } else {
             $navMenu.animate({left: '0'}, 500, function(){
                 transitioning = false;
             });
           }
        }
    });
});

If you want it to respond when you click, then the animate logic needs to be inside of the click event handler. Plus you are setting the 'clicked' data attribute to true every time so it wouldn't change. This serves as a toggle:

$(this).data('clicked', !$(this).data('clicked'));