Can't get Javascript timeout event to execute - javascript

I have a onClick function that works to move boxes on and off the webpage when the screen is clicked. I'm trying to convert this code so that the movement will happen automatically every four seconds. The problem is that the timeout event most likely needs to be happening inside the main function, because of the functions already repetitive nature, and that's where I'm stuck.
This is the working code:
<script>
$('.box').click(function() {
$('.box').each( function() {
if ($(this).offset().left < 0) {
$(this).css("left", "150%");
}
});
$(this).animate({
left: '-56%'
}, 500);
if ($(this).next().size() > 0) {
$(this).next().animate({
left: '50%'
}, 500);
} else {
$(this).prevAll().last().animate({
left: '50%'
}, 500);
}
});
</script>
And this is what I've tried for the timeout:
<script>
window.onload = function(){
setTimeout(boxMove, 1000);
};
function boxMove() {
$('.box').each( function() {
if ($(this).offset().left < 0) {
$(this).css("left", "150%");
}
});
$(this).animate({
left: '-56%'
}, 500);
if ($(this).next().size() > 0) {
$(this).next().animate({
left: '50%'
}, 500);
} else {
$(this).prevAll().last().animate({
left: '50%'
}, 500);
}
}
</script>

To make sure I am understanding correctly, you no longer want the click to clear this box, but rather want it to clear automatically 4 seconds after the page loads.
Your code is close, it just looks like you missed some closing brackets when converting the code. Try this:
window.onload = function(){
setTimeout(boxMove, 1000);
};
function boxMove() {
$('.box').each( function() {
if ($(this).offset().left < 0) {
$(this).css("left", "150%");
}
$(this).animate({
left: '-56%'
}, 500);
if ($(this).next().size() > 0) {
$(this).next().animate({
left: '50%'
}, 500);
} else {
$(this).prevAll().last().animate({
left: '50%'
}, 500);
}
});
}
Assumptions:
Your DOM manipulation with jQuery was functioning as you expect it
to now prior to converting to a timeout.
You only need to clear these boxes once and they never return. If they do return and you want to clear them every 4 seconds regularly, change setTimeout to setInterval.

Related

Stop banner on mouseover

I have created a banner on my site, but I can't make the banner stop on mouseover. I just tried mouseover and hover with jQuery. I expect to stop the banner on mouseover
function mostrarBanner(indice) {
clearInterval(executar);
$('.carousel-banner .item-carousel').css({
'opacity': '0',
'z-index': '0'
});
$('.carousel-banner .item-carousel').eq(banner).css({
'opacity': '1',
'z-index': '1'
});
executar = setInterval(function() {
$('.carousel-banner .next').trigger('click');
}, 1000);
$('#banner').hover(function() {
console.log("DENTRO");
}, function() {
console.log("FORA");
});
}
var executar = setInterval(function() {
$('.carousel-banner .next').trigger('click');
}, 1000);
var banner = 0;
mostrarBanner(banner);
So either you need to cancel the interval and recreate it or you can just use a variable to not call the code.
var paused = false
executar = setInterval(function() {
if (paused) return
$('.carousel-banner .next').trigger('click');
}, 1000);
$('#banner').hover(function() {
paused = true
}, function() {
paused = false
});

jquery animate is very buggy

I am using JQuery animate to animate an image down when scrolled 100 or more pixels. Then when I scroll back to the top it needs to go back in original state. Instead of that on the way back it just goes up and down all over again until it finaly stops.
How can I fix that?
$(document).ready(function() {
$(window).scroll(function() {
if ($(this).scrollTop() >= 100) {
//alert('scrolled');
$('.flipje_pas_image').animate({
top: -50
}, 1000);
}
if ($(this).scrollTop() < 100) {
$('.flipje_pas_image').animate({
top: -450
}, 1000);
}
});
});
you need to use a a boolean state that flips when the if condition is met that makes the animation happen once instead eavery scroll event
like this
$(document).ready(function() {
var once = false;
$(window).scroll(function() {
if ($(this).scrollTop() >= 100) {
//alert('scrolled');
if(!once){
once = true
console.log('ssd' , once)
$('.flipje_pas_imag').animate({
top: -50
}, 1000);
}
}
if ($(this).scrollTop() < 100) {
if(once){
once = false;
$('.flipje_pas_imag').animate({
top: -450
}, 1000);
}
}
});
});

How to add if statements to loop the images around?

This code makes the 'li' move like I want to but when I get to the last 'li' and click next it keeps moving and the 'li' moves out of the users view. I want to know how to loop it so the first 'li' shows up again.
<script type="text/javascript">
$(document).ready(function() {
$('#right').click(function() {
$('.carousel-inner li').animate({
right: '+=292px'
}, 500);
});
$('#left').click(function() {
$('.carousel-inner li').animate({
right: '-=292px'
}, 500);
});
});
</script>
Here is a Fiddle to see an example
This should solve your problem:
$(document).ready(function () {
var inner = $('.carousel-inner'),
slides = inner.find('li'),
width = slides.eq(0).outerWidth(true),
max = (width * slides.length) - width;
$('#right, #left').on('click', function () {
var currRight = parseInt(inner.css('right'), 10), move;
if (this.id === 'right') {
move = currRight === max ? 0 : currRight+width;
} else {
move = currRight === 0 ? max : currRight-width;
}
inner.animate({ right: move }, 500);
});
});
The top four lines cache elements and set up a few basic variables such as the max right value that can used and the width of the slides.
I've then combined the click events to avoid repetition. The first line of the click event defines currRight as $('.carousel-inner')'s current CSS right value as well as move which is used later on.
if (this.id === 'right'){ /* #right */ }else{ /* #left */ } checks whether the id of the clicked element is right or left. The code inside the if statement just checks to see whether the slider is at zero (the beginning) or max (the end) and then sets the move variable to the correct value.
Here it is working: http://jsfiddle.net/mFxcq/10/
Update: To make the slides move on a timer add this after the click event is attached:
function setTimer(){
clearTimeout(window.slideTimer);
window.slideTimer = setTimeout(function(){ $('#right').trigger('click'); }, 5000);
};
setTimer();
Then add setTimer(); right after inner.animate({ right: move }, 500); and everything will work as expected.
Here it is working: http://jsfiddle.net/mFxcq/14/
Add a totalItems variable which will represent the total number of items in the carousel, and a currentItem variable which will represent the number of the current item being displayed (i.e. a number from 1 to totalItems). Then, simply check if it's the last item, and if it is, move the position back to the first one. Check out the revised fiddle, where it works in both directions. Here's example JavaScript, with everything written out for clarity.
var totalItems = $('.carousel-inner li').length;
var currentItem = 1;
$('#right').click(function () {
if (currentItem === totalItems) {
// We've reached the end -- go to the beginning again
$('.carousel-inner li').animate({
right: '-=' + 292 * (totalItems-1) + 'px'
}, 500);
currentItem = 1;
} else {
$('.carousel-inner li').animate({
right: '+=292px'
}, 500);
currentItem += 1;
}
});
$('#left').click(function () {
if (currentItem === 1) {
// We're at the beginning -- loop back to the end
$('.carousel-inner li').animate({
right: '+=' + 292 * (totalItems-1) + 'px'
}, 500);
currentItem = totalItems;
} else {
$('.carousel-inner li').animate({
right: '-=292px'
}, 500);
currentItem -= 1;
}
});
Take a look at this fiddle for a working approach. For the right click.
Basically, each time you click "Right", you'll test to compare the distance traveled by the items and compare that to the maximum distance allowed based on the total number of items.
var slideWidth = 292;
$('#right').click(function() {
if(parseInt($('.carousel-inner li').css('right')) == slideWidth*($('.carousel-inner li').length-1)) {
$('.carousel-inner li').animate({
right: '0px'
, 500);
}
else {
$('.carousel-inner li').animate({
right: '+=' + slideWidth + 'px'
}, 500);
}
});

If no mouse over hide

I have a link that shows a div on mouse over.
On mouse out I hide the div again.
Yet, if the user never mouse overs the div after it opens then it stays open so I need to hide the div after a certain time.
Since these are 2 elements (link and a div) I do not think I can use .hover. How would I best write this to hide .tooltip-profile after 10 seconds of no mouse over?
$("#profile").mouseenter(function(){
var position = $(".tooltip-profile").offset();
$(".tooltip-profile").css( { position: "absolute", left: "720px", top: "-110px" } );
$(".tooltip-profile").fadeIn(500);
} );
$(".tooltip-profile").mouseleave(function(){
$(".tooltip-profile").fadeOut(500);
} );
You need to provide a callback function to your fadeIn() which defines a timeout of 10 seconds. When reached, the time out will fadeOut() the element:
$("#profile").mouseenter(function () {
var position = $(".tooltip-profile").offset();
$(".tooltip-profile").css({
position: "absolute",
left: "720px",
top: "-110px"
});
$(".tooltip-profile").fadeIn(500, function () {
setTimeOut(function () {
$(".tooltip-profile").fadeOut(500);
}, 10000);
});
});
$(".tooltip-profile").mouseleave(function () {
$(".tooltip-profile").fadeOut(500);
});
Wait for some time using setTimeout on mouseleave during this time if mouse is again on link or tooltip don't hide tooltip.
var keepOpend ;
$("#profile").mouseenter(function(){ keepOpend = true;
var position = $(".tooltip-profile").offset();
$(".tooltip-profile").css( { position: "absolute", left: "720px", top: "-110px" } );
$(".tooltip-profile").fadeIn(500);
}).mouseleave(function(){
keepOpend = false;
setTimeout(function(){
!keepOpend && $(".tooltip-profile").fadeOut(500);
}, 500);
});
$(".tooltip-profile").mouseleave(function(){
keepOpend = false;
setTimeout(function(){
!keepOpend && $(".tooltip-profile").fadeOut(500);
}, 500);
}).mouseenter(function(){
keepOpend = true;
});

Making click events into touch events when run on tablets

I have made a spelling game for primary school children. I want to make the click events in my game touch events so it can be compatible on tablets. Is there a way I can put them alongside my click events so that one program is compatible to both, or will I have to make a tablet version?
Here I have the code for one of my click events as an example
$('.drag').on('click', function(e) {
e.preventDefault();
if (animation) return;
animation = true;
setTimeout(function() {
animation = false;
}, 700);
$(".minibutton").css('visibility', 'hidden');
$('.next').css('visibility', 'hidden');
var target = $('.drop-box.spellword:not(.occupied):first');
var targetPos = target.position();
var currentPos = $(this).offset();
var b = $(this);
if (target.length) {
target.addClass("occupied");
b.clone().addClass(
b.data("letter") == target.data("letter") ? "wordglow3" : "wordglow").appendTo("table").css({
background: "transparent",
position: "absolute",
top: currentPos.top,
left: currentPos.left
}).animate({
top: targetPos.top,
left: targetPos.left
}, "slow", function() {
$(this).css({
top: 0,
left: 0
}).appendTo(target);
var spellWord = $('.drop-box.spellword');
if (!spellWord.filter(':not(.occupied)').length) {
var wordIsCorrect = 0;
spellWord.each(function() {
if ($(this).data("letter") == $(this).find("div").data("letter")) {
wordIsCorrect++;
}
});
if (spellWord.length == wordIsCorrect) {
spellWord.addClass('wordglow2');
$(right).val('Right!');
$(right).show();
success.play();
$(wrong).hide();
score.right++;
score.attempts++;
if (score.right == 3) {
$('.answers').css('visibility', 'visible');
$('.answers').html("Well done! </br> You correctly spelt " + score.right + ". </br> Keep it up.").show();
$('table').fadeOut(3000);
$('.right').hide();
$('.box-style2').hide();
$('.box-style').hide();
$('.picstyle').hide();
$('.play').hide();
$('.minibutton2').hide();
$("#mysoundclip").attr('src', listOfWords[rndWord].audio);
audio.stop();
$("#mypic").attr('src', listOfWords[rndWord].pic);
pic.hide();
}
setTimeout(function() {
jQuery('.minibutton').trigger('click');
}, 1500);
setTimeout(function() {
jQuery(right).hide();
}, 1500);
} else {
//spellWord.addClass("wordglow4").css('color', 'transparent');
$(wrong).val('Wrong!');
$(wrong).show();
failure.play();
$(right).hide();
score.wrong++;
score.attempts++;
if (score.wrong == 3) {
$(".minibutton").css('visibility', 'visible');
$('.next').css('visibility', 'visible');
}
$('.drop-box.spellword').animate({
'opacity': 1
}, 1500, function() {
$(this).removeClass('wordglow4').removeClass('occupied').html('')
});
setTimeout(function() {
jQuery(wrong).hide();
}, 1500);
}
}
});
}
});
Can someone point me in the right direction as I have never done this before.
Here is a fiddle to help (Sound warning!!) http://jsfiddle.net/smilburn/7Y7A5/8/
You could add the tap event and include jQuery Mobile in your mobile version.
$('.drag').on('click tap', function(e) {...}

Categories

Resources