Nick Nick - 6 months ago 20
Javascript Question

jquery slideDown, slideUp wiggling

I am new to jquery and have problem with one part of my script. basically I am making dropdown div when mouse is over the button, but div starts moving up and down like crazy. here is what i have done: `

<script type="text/javascript">
public var boolean opened = false;
$("#drop1").slideUp();
$("#first").mouseover(function(){
$("#drop1").slideDown();

});
$("#first").mouseout(function(){

$("#drop1").slideUp();

});
});




also I tried using boolean variable but it gives me error.

<script type="text/javascript">
$(document).ready(function(){
public var boolean opened = false;
$("#drop1").slideUp();
$("#first").mouseover(function(){
if(!opened){
$("#drop1").slideDown();
opened = true;
}
});
$("#first").mouseout(function(){
if(opened){
$("#drop1").slideUp();
opened = false;
}
});
});




here is HTML if you want, but I think there is everything ok.

<link rel="stylesheet" type="text/css" href="design.css">
<div id="first" style="position: absolute; left: 0px;">
<a class="btn" href = "TheShooter/Launcher.exe" ><b>LAN shooter project</b></a>

<div id="drop1">
<a href = "TheShooter/index.php"><em>shooter project main page</em></a> <br/>
info: Local Area Network multiplayer game, made with unity. Project not finished yet, but sometimes fun to play. <br/>
controls: walking: w,a,s,d<br/>
shoot: LMB.<br/>
zoom: RMB.
</div>
</div>


Thanks for any help.

--Nick.

Answer

So it looks like you might be more used to strongly typed languages like C#. JavaScript and its library jQuery are loosely typed, meaning you don't declare scope or type. Here's your code above cleaned up a bit to use correct syntax and solve the issues you're seeing:

$(document).ready(function(){
  var opened = false;
  // Instead of sliding this up, give the #drop1 element
  // a property of display: none; to start - then remove the line below
  $("#drop1").slideUp();
  $("#first").mouseover(function(){
    if(!opened){
      // Below, I'm using a callback, which means the boolean
      // won't update to true until after the animation is finished
      $("#drop1").slideDown(400, function() {
        opened = true;
      });
    }
  })// Since it's the same element, we can chain events
  .mouseout(function(){
    if(opened){
      // Another callback
      $("#drop1").slideUp(400, function() {
        opened = false;
      });
    }
  }
});

});

Let me know if you have any questions about the above!

Comments