Paranoia Paranoia - 2 months ago 15
jQuery Question

Change Mouseenter and Mouseleave to Click

I have a element which shows up when you hover with a mouse. Now we want to change this to click and not mouseenter or -leave. What we have:

$('#element').mouseenter(function(){
$(this).stop().animate({'left': '0px'}, 500);
}).mouseleave(function(){
$(this).stop().animate({'left': -($('#element').width()-10)}, 500);
});


The HTML

<div class="element" id="element"> </div>


The CSS

.element {
position: fixed;
top: 0px;
left: 0px;
height: 100%;
z-index: 1000;
}


We tried to change it to this, but this doesn't work:

$('#element').click(function(){
$(this).stop().animate({'left': '0px'}, 500);
}).mouseleave(function(){
$(this).stop().click({'left': -($('#element').width()-10)}, 500);
});


We just want to slide open on click and slide back out on click again, and not on mouseevent like it is now.

Answer

One way is to use a boolean to know if it's in the visible position then toggle the boolean, var left=false;.

var left = false;
$('#element').click(function() {
  if (left) {
    $(this).stop().animate({
      'left': '0px'
    }, 500);
    left=false;
  } else {
    $(this).stop().animate({
      'left': -($('#element').width() - 10)
    }, 500);
    left=true;
  }
});
.element {
  position: fixed;
  top: 0px;
  left: 0px;
  height: 100%;
  z-index: 1000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element" id="element">Element</div>

An alternate method is to use jquery to get the position and animate it based on position, $(this).position().left

$('#element').click(function() {
  if ($(this).position().left!=0) {
    $(this).stop().animate({
      'left': '0px'
    }, 500);
  } else {
    $(this).stop().animate({
      'left': -($('#element').width() - 10)
    }, 500);
  }
});
.element {
  position: fixed;
  top: 0px;
  left: 0px;
  height: 100%;
  z-index: 1000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element" id="element">Element</div>