Search This Blog

Tuesday 8 April 2014

Append and Animate ONCE with jQuery on mouse action

Using jQuery you can see that appending a text portion or adding an animation to an element on the mouse passage (or on click) brings to an unpleasant loop effect. 



It affects non only appending (or prepending) but each action you assign to the element, also animations, probably you won't see anything, but the CSS will change constantly every time you move the mouse over the element with a unnecessary waste of resources.

Lets make an example, append a paragraph to another on mouse-over could look like this:
1) here the HTML:
 
HeLLo WoRld!
2) here the jQuery snippet:
$( "#animateonce" ).hover(function()
 {
 $(this).append('

this goes in loop

'); });

But try to move the mouse pointer on "Hello World" more times and see what happens:


So, to avoid this you have to use the function: one()
Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
Applying the method will look like:

$( "#animateonce" ).one("mouseenter", function(e) {
       ...
});

Now, let's add a text with some animations:

1) a little more HTML:
 
So long and
thanks for all the fish

2) format it with this CSS:
#animateonce{
 font-size:1em;
 }
.solong{
 position:absolute;
 top:0;
 left:0;
 }
.fish{
 visibility: hidden;
 opacity: 0.0;
 position:absolute;
 top:0;
 right:0;
 }
.answer{
 width:100%
 text-align:center;
 position:absolute;
 top:10%;
 right:50%;
 }
3) then animate it in this way:

$( "#animateonce" ).one("mouseenter", function(e) 
 {
 //animate from left to right and dissolve with css opacity in 2sec
 $(".solong" ).animate({paddingLeft:'40%', opacity: 0.0}, 2000);
 //animate from right to left and make visible in 2sec
 $(".fish").css('visibility', 'visible').animate({marginRight:'40%', opacity: 1.0}, 2000);
 //appen a div to #animateonce and increase font size
 $(this).append('
42
').animate({fontSize:'2em'}, 2000); //increase the fon size of appended string $('.answer').animate({fontSize:'5em'}, 2000); }); });

And then move the mouse over the text below to see the final effect:

No comments:

Post a Comment