javascript - ignore timeout on click - javascript

I have a slideshow which works fine, leaving a 3 second gap between images.
I also have a set of dynamically generated links which when clicked on, the next image is corresponds to that link.
What I want to do is skip the 3 second time out when one of these links is clicked - then restart the timeout after the image is changed.
Code below:
$(document).ready(function() {
var images=new Array();
var totalimages=6;
var totallinks=totalimages;
var nextimage=2;
while (totallinks>0) {
$(".quicklinks").prepend("<a href='#' class='"+(parseInt(totallinks))+"' onclick='return false'>"+(parseInt(totallinks))+"</a> ");
totallinks--;
}
function runSlides() {
if(runSlides.opt) {
setTimeout(doSlideshow,3000);
}
}
function doSlideshow()
{
if($('.myImage').length!=0)
$('.myImage').fadeOut(500,function(){slideshowFadeIn();$(this).remove();});
else
slideshowFadeIn();
}
function slideshowFadeIn()
{
if(nextimage>=images.length)
nextimage=1;
$('.container').prepend($('<img class="myImage" src="'+images[nextimage]+'" style="display:none;">').fadeIn(500,function() {
runSlides();
nextimage++;
}));
}
if(runSlides.opt) {} else {
images=[];
totalimages=6;
while (totalimages>0) {
images[totalimages]='/images/properties/images/BK-0'+parseInt(totalimages)+'.jpg';
totalimages--;
}
runSlides.opt = true;
runSlides();
}
$(".quicklinks a").live('click', function() {
nextimage=$(this).attr("class");
});
});

You can stop a timeout using this code:
var t = setTimeout(myFunction,3000);
clearTimeout(t);
Using this, you can abort your timeout when the user clicks the button and call the function directly. Then you can restart the timeout.
Hope this helps.

Related

.on('click', function(){}) only working on first click

I'm making a Blackjack game to exercise my Javascript skills. I had a bunch of alert() messages tied to the betting function to prevent invalid entries. In updating the code to have a more elegant message style than a browser alert, I wrote a function called alertModal() that pops up a message on the screen and then fades away. The message pops up the first time a user tries to enter an invalid bet, but does not pop up any other messages if the bet is invalid-- nothing happens. I know the placeBet() function is still running when the user clicks again, because if the bet is valid, dealFirstCards() runs and the game proceeds. So it seems to me that for some reason, the if/else portion of the placeBet() function is only running on the first click...
The game is live and running with this code at http://cnb-blackjack.netlify.com/game.html
Here is the javascript code in question:
// Player places a bet
$('div.bet').on('click', function() {
$(this).removeClass('glow');
$('.bet-button').addClass('glow');
});
$('.bet-button').on('click', function() {
event.preventDefault();
if (!placeBet.called) {
placeBet();
}
});
// PLACE BET
function placeBet() {
var $bet = parseInt($('.bet-input').val())
var $bank = parseInt($('.player-bank').text())
var $currentBet = $('.current-bet');
if (!isNaN($bet) && $bet <= $bank && $bet !== 0) {
$currentBet.text(' $' + $bet);
$('.bet input[type="text"]').val('');
$('.place-bet .hideaway').slideUp();
$('.player-bank').text($bank - $bet);
placeBet.called = true;
dealFirstCards();
} else if ($bet > $bank) {
var $message = 'Bet cannot exceed the amount in your Bank!';
alertModal($message);
} else if (isNaN($bet)) {
var $message = 'Enter a number, without "$".';
alertModal($message);
} else if ($bet === 0) {
var $message = "Betting nothing won't get you very far...";
alertModal($message);
}
}
// SHOW MODAL
function alertModal(message) {
$popUp = $('.alert-message');
$('.modal').removeClass('hide');
$popUp.text(message);
setTimeout(function() {
$('.modal').fadeOut(1000);
}, 1000);
}
function alertModal(message) {
$popUp = $('.alert-message');
$('.modal').show();
$popUp.text(message);
setTimeout(function() {
$('.modal').fadeOut(1000);
}, 1000);
}
As comments have explained, fadeOut is leaving the modal hidden after the first time it's clicked. Just call $(element).show(); on the modal to show it again and let fadeOut remove it.

prevent animation double click issue

Hi I have problem with my slider please visit this site and check http://paruyr.bl.ee/
after click on my arrows it becomes work in an asynchronous way, ones it changes very fast and then slow and it repeats.
I think it is from start slider and stop slider.
var sliderPrev = 0,
sliderNext = 1;
$("#slider > img").fadeIn(1000);
startSlider();
function startSlider(){
count = $("#slider > img").size();
loop = setInterval(function(){
if (sliderNext>(count-1)) {
sliderNext = 0;
sliderPrev = 0;
};
$("#slider").animate({left:+(-sliderNext)*100+'%'},900);
sliderPrev = sliderNext;
sliderNext=sliderNext+1;
},6000)
}
function prev () {
var newSlide=sliderPrev-1;
showSlide(newSlide);
}
function next () {
var newSlide=sliderPrev+1;
showSlide(sliderNext);
}
function stopLoop () {
window.clearInterval(loop);
}
function showSlide(id) {
stopLoop();
if (id>(count-1)) {
id = 0;
} else if(id<0){
id=count-1;
}
$("#slider").animate({left:+(-id)*100+'%'},900);
sliderPrev = id;
sliderNext=id+1;
startSlider();
};
$("#slider, .arrows").hover(function() {
stopLoop()
}, function() {
startSlider()
});
function onlyNext () {
var newSlide=sliderPrev+1;
onlyShowSlide(newSlide);
}
function onlyShowSlide(id) {
if (id>(count-1)) {
id = 0;
} else if(id<0){
id=count-1;
}
$("#slider").animate({left:+(-id)*100+'%'},900);
sliderPrev = id;
sliderNext=id+1;
};
I think the best option would be to check if the animation is in progress and prevent the action if it is, something like this:
function prev () {
if(!$('#slider').is(":animated"))
{
var newSlide=sliderPrev-1;
showSlide(newSlide);
}
}
function next () {
if(!$('#slider').is(":animated"))
{
var newSlide=sliderPrev+1;
showSlide(sliderNext);
}
}
To illustrate the difference between this and just sticking a stop() in, check this JSFiddle. You will notice some choppy movements if you click multiple times in the stop() version.
What I would do is add a class to your slider when the animation starts and remove the class when it finishes:
$("#slider").animate({left:+(-id)*100+'%'}, {
duration: 900,
start: function() {
$('#slider').addClass('blocked');
},
complete: function() {
$('#slider').removeClass('blocked');
}
});
Now check on each click event if the slider is blocked or not:
function next () {
if (!$('#slider').hasClass('blocked')) {
var newSlide=sliderPrev+1;
showSlide(sliderNext);
}
}
This is a very simple solution, I'm sure there is a better one.
EDIT: As marcjae pointed out, you could stop the animations from queuing. This means when you double click, the slideshow still will move 2 slides. With my approach the second click will be ignored completely.
You can use a variable flag to control if the animation is still being done, or simply use .stop() to avoid stacking the animation.
$("#pull").click(function(){
$("#togle-menu").stop().slideToggle("slow");
});
It is occurring because your animations are being queued.
Try adding:
.stop( true, true )
Before each of your animation methods. i.e.
$("#slider").stop( true, true ).animate({left:+(-id)*100+'%'},900);
The answers about stop are good, but you have a bigger issue that is causing the described behavior. The issue is here:
$("#slider, .arrows").hover(function() {
stopLoop()
}, function() {
startSlider()
});
You have bound this to the .arrows as well as the #slider and the arrows are contained within the slider. So, when you mouse out of an arrow and then out of the entire slider, you are calling start twice in a row without calling stop between. You can see this if you hover onto the arrow and then off of the slider multiple times in a row. The slides will change many times after 6 seconds.
Similarly, consider the case of a single click:
Enter the `#slider` [stopLoop]
Enter the `.arrows` [stopLoop]
Click the arrow [stopLoop]
[startSlider]
Leave the `.arrows` [startSlider]
Leave the `#slider` [startSlider]
As you can see from this sequence of events, startSlider is called 3 times in a row without calling stopLoop inbetween. The result is 3 intervals created, 2 of which will not be stopped the next time stopLoop is called.
You should just have this hover on the #slider and more importantly, add a call to stopLoop as the first step in startSlider. That will ensure that the interval is always cleared before creating a new one.
$("#slider").hover(function() {
stopLoop()
}, function() {
startSlider()
});
function startSlider(){
stopLoop();
/* start the slider */
}

how to make this custom animation by changing background position in jquery using intervals?

I am trying to make a small animation by moving the background position (frames) of the image which is background on my div. I am using Jquery to make this animation happen. I have 6 frames on the background image, first frame starting at 0,0px, second starting at 85px,0, third at 172px,0 and so on.
I want to transition between these frames until stop is clicked. My jquery code is pasted below. I have made an array for the pixels to move across. I want each frame to hold upto 1000 milliseconds, then transition to next frame. I am going wrong somewhere but unable to figure out where..
here is my code
$(document).ready(function () {
var timer;
$("#clickMe").click(function() {
//alert("you are here");
timer=setInterval(moveframe,1000);
});
$("#stop").click(function() {
clearInterval(timer);
});
});
function moveframe() {
var framespx=[0,85,172,256,512,1024];
for (var i=0;i<framespx.length;i++) {
alert("you ar here");
var xPos=framespx[i]+"px ";
var yPos="0px";
$('.fixed').css({backgroundPosition: xPos+yPos});
}
}
your code looks like has some logical error,run your code ,just can see the same background.
try:
$(document).ready(function () {
var timer;
$("#clickMe").click(function() {
//alert("you are here");
timer=setInterval(moveframe,1000);
});
$("#stop").click(function() {
clearInterval(timer);
});
});
var j=0;
function moveframe() {
var framespx=[0,85,172,256,512,1024];
for (var i=0;i<framespx.length;i++) {
if (j%framespx.length == i){
alert("you ar here");
var xPos=framespx[i]+"px ";
var yPos="0px";
$('.fixed').css({backgroundPosition: xPos+yPos});
j++
break;
}
}
}
css({'background-position': xPos+' '+yPos});
okay the above attribute value is a bit confusing for me, hopefully that is correct but with more surety;
css('background-position-x', xPos);
css('background-position-y', yPos);
Now I don't think for loop is mandatory here
var posAry=[0,85,172,256,512,1024];
var currPos=0;
var timer;
$(document).ready(function () {
$("#start").click(function() {
timer=setInterval(move,1000);
});
$("#stop").click(function() {
clearInterval(timer);
});
});
function move() {
$('.fixed').css({'margin-left': posAry[currPos]+'px' }); /**you can change it to background postion/padding/... as needed by you**/
currPos++;
if(currPos==(posAry.length))
currPos=0; // for looping back
}
http://jsfiddle.net/7PvwN/1/

need to modify this jquery pop menu script to work with ajax

I am using this script from: http://pop.seaofclouds.com/
The problem is if you call the script multiple times it causes a cascading effect of a pop-out within a pop-out for as many times as you call the script.
I'm trying to figure out how to prevent it from executing when the popout has already been set. Here's the script:
//
// pop! for jQuery
// v0.2 requires jQuery v1.2 or later
//
// Licensed under the MIT:
// http://www.opensource.org/licenses/mit-license.php
//
// Copyright 2007,2008 SEAOFCLOUDS [http://seaofclouds.com]
//
(function($) {
$.pop = function(options){
// inject html wrapper
function initpops (){
$(".pop").each(function() {
var pop_classes = $(this).attr("class");
if ( $(this).find('.pop_menu').length) {
// do nothing
} else {
$(this).addClass("pop_menu");
$(this).wrap("<div class='"+pop_classes+"'></div>");
$(".pop_menu").attr("class", "pop_menu");
$(this).before(" \
<div class='pop_toggle'></div> \
");
}
});
}
initpops();
// assign reverse z-indexes to each pop
var totalpops = $(".pop").length + 100;
$(".pop").each(function(i) {
var popzindex = totalpops - i;
$(this).css({ zIndex: popzindex });
});
// close pops if user clicks outside of pop
activePop = null;
function closeInactivePop() {
$(".pop").each(function (i) {
if ($(this).hasClass('active') && i!=activePop) {
$(this).removeClass('active');
}
});
return false;
}
$(".pop").mouseover(function() { activePop = $(".pop").index(this); });
$(".pop").mouseout(function() { activePop = null; });
$("body").on("click", ".pop", function(){
closeInactivePop();
});
// toggle that pop
$("body").on("click", ".pop_toggle", function(){
$(this).parent(".pop").toggleClass("active");
});
}
})(jQuery);
now when i load this script on an ajax call the new pop-out menus work but the old ones do not react to the onclick event.
You shouldn't mess with the plugin. It works exactly like it should.
Better show us how you call this on elements that you already have.
Also I don't like this plugin. Better use something from JqueryUI
You can do such thing in much easier way.
[edit]
I tried your first code (the plugin) and it works correctly for me.
[edit]
OK. I get it. You call $.pop(); multiple times. You shouldn't! Calling $.pop(); will pin up the drop down menu to all elements that has class="pop". This is the reason why you have such funny stack.
Just use $.pop(); once.
Plugin doesn't give ability to connect NEW elements that was dynamically created on the page.
Removed pop from ajax call and just called this on success:
$(".pop").each(function() {
var pop_classes = $(this).attr("class");
if ( $(this).find('.pop_menu').length) {
// do nothing
} else {
$(this).addClass("pop_menu");
$(this).wrap("<div class='"+pop_classes+"'></div>");
$(".pop_menu").attr("class", "pop_menu");
$(this).before(" \
<div class='pop_toggle'></div> \
");
}
});
// assign reverse z-indexes to each pop
var totalpops = $(".pop").length + 100;
$(".pop").each(function(i) {
var popzindex = totalpops - i;
$(this).css({ zIndex: popzindex });
});
// close pops if user clicks outside of pop
activePop = null;
function closeInactivePop() {
$(".pop").each(function (i) {
if ($(this).hasClass('active') && i!=activePop) {
$(this).removeClass('active');
}
});
return false;
}
$(".pop").mouseover(function() { activePop = $(".pop").index(this); });
$(".pop").mouseout(function() { activePop = null; });

jQuery function attr() doesn't always update img src attribute

Context: On my product website I have a link for a Java webstart application (in several locations).
My goal: prevent users from double-clicking, i. e. only "fire" on first click, wait 3 secs before enabling the link again. On clicking, change the link image to something that signifies that the application is launching.
My solution works, except the image doesn't update reliably after clicking. The commented out debug output gives me the right content and the mouseover callbacks work correctly, too.
See it running here: http://www.auctober.de/beta/ (click the Button "jetzt starten").
BTW: if anybody has a better way of calling a function with a delay than that dummy-animate, let me know.
JavaScript:
<script type="text/javascript">
<!--
allowClick = true;
linkElements = "a[href='http://www.auctober.de/beta/?startjnlp=true&rand=1249026819']";
$(document).ready(function() {
$('#jnlpLink').mouseover(function() {
if ( allowClick ) {
setImage('images/jetzt_starten2.gif');
}
});
$('#jnlpLink').mouseout(function() {
if ( allowClick ) {
setImage('images/jetzt_starten.gif');
}
});
$(linkElements).click(function(evt) {
if ( ! allowClick ) {
evt.preventDefault();
}
else {
setAllowClick(false);
var altContent = $('#jnlpLink').attr('altContent');
var oldContent = $('#launchImg').attr('src');
setImage(altContent);
$(this).animate({opacity: 1.0}, 3000, "", function() {
setAllowClick(true);
setImage(oldContent);
});
}
});
});
function setAllowClick(flag) {
allowClick = flag;
}
function setImage(imgSrc) {
//$('#debug').html("img:"+imgSrc);
$('#launchImg').attr('src', imgSrc);
}
//-->
</script>
A delay can be achieved with the setTimeout function
setTimeout(function() { alert('something')}, 3000);//3 secs
And for your src problem, try:
$('#launchImg')[0].src = imgSrc;
Check out the BlockUI plug-in. Sounds like it could be what you're looking for.
You'll find a nice demo here.
...or just use:
$(this).animate({opacity: '1'}, 1000);
wherever you want in your code, where $(this) is something that is already at opacity=1...which means everything seemingly pauses for one second. I use this all the time.
Add this variable at the top of your script:
var timer;
Implement this function:
function setFlagAndImage(flag) {
setAllowClick(flag);
setImage();
}
And then replace the dummy animation with:
timer = window.setTimeout(function() { setFlagAndImage(true); }, 3000);
If something else then happens and you want to stop the timer, you can just call:
window.clearTimeout(timer);

Categories