jQuery weird interaction between .hide() and .show()

Viewed 86

I have two elements in my website in the same container. One is visible (display: block), and one is hidden (display: none). On an event, I want the visible element to hide, and the hidden element to show. The problem is, when I show the hidden element after hiding the visible element, it always has a split second where it jumps from its previous stacked position on top of the visible element to the position it should be in:

Velocity(document.getElementById("originallyVisible"), { opacity: 0 }, { display: "none" }, {duration: 500});
Velocity(document.getElementById("originallyHidden"),{ opacity: 1 },{ display: "block" },{duration: 500, delay: 200000});

Note: the code is in velocity.js, but it should be equivalent to .hide() and .show() in native jQuery, according to docs. Please let me know if the issue is velocity specific.

I thought this was a conflict with the two commands being two close to eachother, so I added a delay to the second command. However, no matter how long the delay is, the issue still prevails.

Why does this happen?

2 Answers

You are specifying both changes with a duration of half a second, which means for about half a second both elements are visible on the screen (one fading in, the other fading out).

If you don't want your elements to jump around, you need to make sure that if both are shown they don't interact negatively with each other - perhaps by setting position: absolute and positioning them on top of each other visually.

(Btw, I'm not sure that delay is right, that's 200 seconds? I wonder if it's doing anything at all.)

Does velocity.js have event callback after animation like JQuery?

In this JQuery callback first will hide an element before show next element:

$("#originallyVisible").fadeOut(300,function(){
    $("#originallyHidden").fadeIn(300);
});

Another way to do it is using css keyframes with smooth effects, setting up timing on every element and adding to originallyVisible some class called .hideElement and originallyHidden apply .showElement

I think it's interesting velocity.js, I'll check it soon. I hope it helps :)

Related