HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Sliding effect with bounce

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
effectbounceslidingwith

Problem

I have used animate.css and jQuery as external libs. Is there a better way of doing what I have done with jQuery?

DEMO



$(document).ready(function () {

$('#test li').on('click', function () {

var className = $(this).attr('class');
$('#test2 > li').each(function () {

var prodName = $(this).data('prod');

if (prodName == className) {

$('#test2 > li').removeClass('bounceInRight').addClass('bounceOutRight');
$this = $(this);
setTimeout(function () {
console.log(this);
$('#test2 > li').addClass('hide')
$this.removeClass('hide bounceOutRight').addClass('bounceInRight');
}, 400);

}
});
})
});

ul#test > li {
display: inline-block;
padding: 10px;
cursor: pointer;
}
#test {
position: fixed;
top: 0;
left: 0;
}
#test2 {
position: fixed;
top: 0;
right: 0;
list-style: none;
}
#test2 > li {
background: yellow;
width: 350px;
height: 600px;
/ transition: height 0.3s ease, width 0.2s ease;/
overflow: hidden;
margin-top: -30px;
padding-top: 30px;
margin-right: -50px;
}
.hide {
display: none;
}



1
2
3

1
2
3

Solution

Your demonstration could benefit from better semantic markup. In particular, the numbers on the left should be treated as navigation links, whose target is the item to be animated. If you remove all JavaScript and CSS, the functionality degrades gracefully.

An additional benefit is that the link directly identifies the item to be manipulated, so that you don't have to locate the element yourself using a var prodName = $(this).data('prod'); if (prodName == className) … check.

You don't need to define a .hide { display: none; } rule in your CSS. The jQuery $.hide() and $.show() methods can do that job.

Take care to localize $this.



$(document).ready(function () {
$('nav > ul > li > a').on('click', function () {
$('li.animated').hide();
$($(this).attr('href')).each(function () {
var $this = $(this);
$this.show()
.removeClass('bounceInRight')
.addClass('bounceOutRight');
setTimeout(function () {
$this.removeClass('bounceOutRight')
.addClass('bounceInRight');
}, 400);
});
})
});

nav > ul > li {
display: inline-block;
padding: 10px;
}
nav > ul > li > a {
color: black;
text-decoration: none;
}
ul {
position: fixed;
top: 0;
right: 0;
list-stlye: none;
}
nav > ul {
right: auto;
left: 0;
}
li.animated {
background: yellow;
width: 350px;
height: 600px;
/ transition: height 0.3s ease, width 0.2s ease;/
overflow: hidden;
margin-top: -30px;
padding-top: 30px;
margin-right: -50px;
}





  • 1



  • 2



  • 3




1
2
3

Context

StackExchange Code Review Q#87148, answer score: 2

Revisions (0)

No revisions yet.