A little while ago I wrote some jQuery code to make a div flip (similar to the Apple Dashboard). I know there is already code that has this idea from Jon Raasch, but this code positioned divs absolutely, which I did not need for my cause.
I just wondered if anyone could give me some advice as to how to tidy this up and make it cleaner.
(function ($) {
$.fn.extend({
jFlip: function (options) {
var defaults = {
trigF: '.flipDiv',
trigB: '.flipDivBack'
};
var o = $.extend({}, defaults, options);
return this.each(function () {
var f = $('.front');
b = $('.back');
margin = f.width() / 2;
width = f.width();
height = f.height();
b.hide().css({
width: '0px',
height: '' + height + 'px',
marginLeft: '' + margin + 'px',
opacity: '0'
});
$(o.trigF).on('click', function () {
var $this = $(this);
$this.parents().closest(f).animate({
width: '0px',
height: '' + height + 'px',
marginLeft: '' + margin + 'px',
opacity: '0'
}, {
duration: 500
});
window.setTimeout(function () {
$this.parents().next(b).animate({
width: '' + width + 'px',
height: '' + height + 'px',
marginLeft: '0px',
opacity: '1'
}, {
duration: 500
});
}, 500);
});
$(o.trigB).on('click', function () {
$(this).parents().closest(b).animate({
width: '0px',
height: '' + height + 'px',
marginLeft: '' +margin + 'px',
opacity: '0',
display: 'none'
}, {
duration: 500
});
var $this = $(this).parents().siblings(f);
window.setTimeout(function () {
$this.stop().animate({
width: '' + width + 'px',
height: '' + height + 'px',
marginLeft: '0px',
opacity: '1'
}, {
duration: 500
});
}, 500);
});
});
}
});
})(jQuery);
The div
structure is this:
<div class="widgetBox">
<div class="front">
<p>Front of the div</p>
<button class="flipDiv">Flip</button>
</div>
<div class="back">
<p>Back of the div</p>
<button class="flipDivBack">Flip Back</button>
</div>
</div>
And this is the initiation:
<script>
$(document).ready(function() {
$('.widgetBox').jFlip();
});
</script>
The only options as of yet however are trigF and trigB, which allows you to specify the name of your buttons which will flip the div.
You can see a jsFiddle of this in action here.