I'm trying to achieve some animation using jQuery. I have it working but I'm 100% sure there is a cleaner better way of doing and I'm hoping someone can point me in the right direction.
Here is my code:
$(document).ready(function () {
$("#1-popup").hide(); // Hides the first popup
$("#2-popup").hide(); // Hides the second popup
$("#1-trigger").toggle(function () {
$("#2-popup").fadeOut("slow"); // Hides the second popup just incase its showing
$("#1-popup").fadeIn("slow"); // Fades in the first popup
}, function () {
$("#1-popup").fadeOut("slow"); // Fades out in the first popup
});
$("#2-trigger").toggle(function () {
$("#1-popup").fadeOut("slow"); // Hides the first popup just incase its showing
$("#2-popup").fadeIn("slow"); // Fades in the second popup
}, function () {
$("#2-popup").fadeOut("slow"); // Fades out the second popup
});
});
Its 开发者_如何学编程a little messy is there anyway to use an if statement in this?
How about being a bit more generic instead of writing code for every popup itself? :-)
<div class="popup" id="popup1">Hi I'm Popup 1</div>
<div class="popup" id="popup2">Hi I'm Popup 2</div>
<a class="trigger" rel="popup1">show popup 1</a>
<a class="trigger" rel="popup2">show popup 2</a>
<script>
var popups = $('.popup').hide();
$('a.trigger').click(function() {
var popup = $('#'+$(this).attr('rel'));
popups.not(popup.fadeIn()).fadeOut();
});
</script>
You could move the toggle code into a seperate function and reuse this for the different triggers. This is more just a general refactoring rather than a jQuery specific improvement:
bindToggleTriggerAndFadePopups($("#1-trigger"), $("#1-popup"), $("#2-popup"))
bindToggleTriggerAndFadePopups($("#2-trigger"), $("#2-popup"), $("#1-popup"))
function bindToggleTriggerAndFadePopups($trigger, $popupToFadeIn, $popupToHide){
$trigger.toggle(
function(){
$popupToHide.fadeOut("slow"); // Hides the first popup just incase its showing
$popupToFadeIn.fadeIn("slow"); // Fades in the second popup
},
function(){
$popupToFadeIn.fadeOut("slow"); // Fades out the second popup
});
}
$(document).ready(function () {
$('#1-popup,#2-popup').hide(); // Hides the first and second popup
$('#1-trigger,#2-trigger').toggle(function () {
var num = parseInt(this.id);
$('#1-popup,#2-popup').not('#'+num+'-popup').fadeOut('slow');
$('#'+num+'-popup').fadeIn('slow');
}, function () {
$('#'+num+'-popup').fadeOut('slow');
});
});
WARNING: you have invalid attribute value for id
, refer here. With that, you'll get serious problems on some browsers.
精彩评论