Reputation: 103
I'm attempting to create various boxes (only one time) in different positions, but I cannot accomplish this, this is the jsFiddle: http://jsfiddle.net/3Y7g3/11/
$(function () {
$(window).scroll(function () {
var popWidth = "44%";
var popHeight = "30%";
function pop(popID) {
$('#'+popID).fadeIn().css({'width':String(popWidth),'height':String(popHeight)
})
};
function block(box, top, left, color) {
var $btn = $('<div data-role="box"></div>');
$("#container").children().append($btn);
$($btn).css("background-color", color).animate({top: top,left: left});
};
var range = $(this).scrollLeft();
if (range > 500 && range < 600) {
pop('popup1')
$('#popup2').fadeOut(function () {
$('#popup2').hide();
});
block('box1', '84%', '10%', '#f04');
} else if (range > 1500 && range < 1600) {
pop('popup2');
$('#popup1').fadeOut(function () {
$('#popup1').hide();
});
block('box2', '84%', '10%', 'yellow');
};
});
});
Upvotes: 1
Views: 99
Reputation: 193261
Change you switch to something like this:
switch (true) {
case (range > 480 && range < 520):
popID = 'popup1';
break;
case (range > 980 && range < 1020):
popID = 'popup2';
break;
}
if (popID) {
$('.popup_block').hide();
$('#' + popID).fadeIn().css({
width: popWidth,
height: popHeight
})
.prepend('<a href="#" class="close"><img src="close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');
}
Basically, here you compare scrollLeft
against range of values which guarantees that you never skip 500
or 1000
event if you scroll fast. Instead of switch you can also use if-else-if
statement.
You also need to hide previous blocks with $('.popup_block').hide();
.
Upvotes: 1
Reputation: 74420
EDIT: i see code not relevant to posted code but to irrelevant jsFiddle...
You should try $('.popup_block').not('#' + popID).finish().hide();
:
$(function () {
$(window).scroll(function () {
var popWidth = "44%";
var popHeight = "30%";
var popID;
var range = $(this).scrollLeft();
switch (range) {
case (500):
popID = 'popup1';
break;
case (1000):
popID = 'popup2';
break;
}
$('.popup_block').not('#' + popID).finish().hide(); //<< call here
$('#' + popID).fadeIn().css({
'width': String(popWidth),
'height': String(popHeight)
}).prepend('<a href="#" class="close"><img src="close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');
});
});
Upvotes: 1