Cafecorridor
Cafecorridor

Reputation: 1609

JQuery mouse event occurring many times, want it only once

I'm trying to create a JQuery slider and I've hit a roadblock. I'm new to both Javascript and JQuery however. Here is my code -

<!DOCTYPE html>
<html>
  <head>
    <title>Experimentation</title>
    <style type="text/css">

#container {
overflow: hidden;
height: 200px;
width: 200px;
}   

#box {
  width: 200px;
  height: 200px;
  background-color: gray;
  z-index: 10000;
  position: relative;
  }


#information {
  position: absolute;
  width: 200px;
  height:200px;
  background-color: black;
  opacity: 0.2;
  top: 150px;
  color: #FFF;
}

#information h3 {
 margin: 3px 3px; 
 text-align: center;
}

    </style>
    <script type="text/javascript" src="jquery-1.4.js"></script>
    <script type="text/javascript">
      var topInitial = "0";
      var topAfter = "150px";

      $(function() {

      /*
      $("#box").mouseover(function(){
      $("#information").css("top",topInitial); }); 


      $("#box").mouseout(function() {
      $("#information").css("top",topAfter); });      
      });
      */

      $("#box").mouseover(function() {  
      $("#information").animate({
      top: 0 }, "slow"); });

      $("#box").mouseout(function() {
      $("#information").animate({
      top: 150 }, "slow"); });

      //New Code
      $("#container").click(function() {
  $("#container").animate({
  margin-left: 30}, "slow"); });

     });
    </script>
  </head>

  <body>

  <div id="container">
  <div id="box">
  <div id="information">
  <h3> Criminal Penguins Having a Ball </h3>
  <p> You have never seen something like this before!</p>
  </div>
  </div>
  </div>

  </body>
</html>

My problem is, the mouseover event is happening many times. Can someone tell me how to rectify this issue? Another important query, since I've only begun to code I'm sure I'll hit some roadblocks in the future as well. Should I then create a new thread with the modified code or will editing this thread work? Please help! :)

Update: I've just added some new code in my Javascript. I want to move the element to the right by 30px. Is this the way to accomplish this task?

Upvotes: 0

Views: 456

Answers (1)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Use mouseenter instead of mouseover. Mouse enter will be called once it enters the element.

Change your function as below,

   $("#box").mouseenter(function() {  
      $("#information").animate({
        top: 0 }, "slow"); 
   });

Also you can change your script like below,

  $("#box").mouseenter(function() {  
     $("#information").animate({
     top: 0 }, "slow"); 
  }).mouseleave(function() {
     $("#information").animate({
     top: 150 }, "slow"); 
  });

You can read about all jQuery mouse events here

Upvotes: 1

Related Questions