Reputation: 13
I have this basic script that makes an element show onmouseenter, and hide onmouseleave. In HTML version works fine, but i need to display it in wordpress; but in WP didn't work.
Firebug shows the following error:
sidebar_animate is not defined
How can I fix this?
<script language="javascript">
function sidebar_animate(px) {
$('#sidebar').animate({
'marginLeft' : px
});
}
</script>
<div id="sidebar" onmouseenter="sidebar_animate('+180px');"
onmouseleave="sidebar_animate('-20px');"
style="background-color: red; width: 240px; height: 100px; position: absolute; left: -180px;" >
This is going to move
</div>
Upvotes: 1
Views: 294
Reputation: 76003
How about binding the event handlers with jQuery so your code is all in one spot:
<script language="javascript">
//wait for document.ready to fire so elements are available to manipulate
$(function () {
//setup object to convert the type of event fired to the pixel offset to apply for the event
var eventToPx = {
mouseenter : 180,
mouseleave : -20
};
//bind an event handler to the `#sidebar` element for `mouseleave` and `mouseenter`
$('#sidebar').on('mouseenter mouseleave', function (event) {
//animate this element's `margin-left` property to the specified number of pixels
//note that jQuery assumes pixels if you omit units
$(this).stop().animate({
marginLeft : eventToPx[event.type]
}, 500);
});
});
</script>
Here is a demo: http://jsfiddle.net/jasper/mYwqE/
Notice that I added .stop()
to your code just before the .animate()
call. It will stop the current animation if a new one is queued, so the animations won't queue-up if the user mouse-over's and mouse-out's the element many times rapidly.
Note that .on()
is new as of jQuery 1.7 and in this case is the same as using .bind()
: http://api.jquery.com/on
Upvotes: 3