简体   繁体   中英

Partially showing/hiding an element with jQuery

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?

The script

<script language="javascript">

    function sidebar_animate(px) {
       $('#sidebar').animate({
       'marginLeft' : px
     });
}
</script>

Body

<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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM