JavaScript SetInterval () is not working after clicking - javascript

Hi I have wrote this code and it suppose to move the object every 3000 ms after clicking on the object, but some how the time its not working, can anyone tell me what I am doing wrong, I am just learning javascript; thank you very much
function move1() {
var im1 = document.images[0];
im1.onclick = function() {
im1.style.left = parseInt(im1.style.left) + 1 + "px";
}
}
function move2() {
var im2 = document.images[1];
im2.onclick = function() {
im2.style.left = parseInt(im2.style.left) + 10 + "px";
}
}
window.onload = function() {
setInterval(move1, 100);
setInterval(move2, 3000);
}

You're doing it the other way round. Every 3000ms you make it possible to move the image by 1px when clicking on it.
function move(el, ms, px) {
/* moves the el every ms by px
returns the interval id to clear the movement */
return setInterval(function() {
el.style.left = parseInt(el.style.left) + px + "px";
}, ms);
}
window.onload = function() {
var im0 = document.images[0];
var im1 = document.images[1];
im0.onclick = function() {
move(im0, 100, 1);
};
im1.onclick = function() {
move(im1, 3000, 10);
};
}

Your move function registers the image on click, but doesn't actually do any moving until the user clicks. What you want is more like this:
function move1() {
var im1 = document.images[0];
im1.style.left = parseInt(im1.style.left) + 1 + "px";
}
function move2() {
var im2 = document.images[1];
im2.style.left = parseInt(im2.style.left) + 10 + "px";
}
window.onload = function() {
var im2 = document.images[1];
im2.onclick = function() {
setInterval(move2, 3000);
}
im1.onclick = function() {
setInterval(move1, 100);
}
}

Related

How do add a timer that resets after each level is completed?

I can't figure out how to add a restarting timer to my simon game. I know setInterval() and SetTimeout but I can't figure out how to have the timer reset for each level if the level is passed within the first 10 seconds. Do I need an if/else to work and concatenate it to level or userClickPattern? I dont know, I tried it all.
Goal:
Have a 10 second timer that starts .click and if the pattern is completed to move to the next sequence if it is not completed then alert("... ) and restart the game. The timer function is at the bottom. Please help me!!!
var buttonColours = ["red", "blue", "green", "yellow"];
var gamePattern = [];
var userClickedPattern = [];
var started = false;
var level = 0;
$(document).keypress(function() {
if (!started) {
$("#level-title").text("Level " + level);
nextSequence();
started = true;
}
});
$(".btn").click(function() {
var userChosenColour = $(this).attr("id");
userClickedPattern.push(userChosenColour);
playSound(userChosenColour);
animatePress(userChosenColour);
checkAnswer(userClickedPattern.length - 1);
});
function checkAnswer(currentLevel) {
if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
console.log("success");
if (userClickedPattern.length === gamePattern.length) {
setTimeout(function() {
nextSequence();
}, 1000);
}
} else {
console.log("wrong");
playSound("wrong");
$("body").addClass("game-over");
setTimeout(function() {
$("body").removeClass("game-over");
}, 200);
$("#level-title").text("Game Over, Press Any Key to Restart");
startOver();
}
}
function nextSequence() {
userClickedPattern = [];
level++;
$("#level-title").text("Level " + level);
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColour = buttonColours[randomNumber];
gamePattern.push(randomChosenColour);
$("#" + randomChosenColour).fadeIn(100).fadeOut(100).fadeIn(100);
playSound(randomChosenColour);
}
function playSound(name) {
var audio = new Audio("sounds/" + name + ".mp3");
audio.play();
}
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
setTimeout(function() {
$("#" + currentColor).removeClass("pressed");
}, 100);
}
function startOver() {
level = 0;
gamePattern = [];
started = false;
}
function timer() {
alert("Out Of Time Better Luck Next time");
playSound("wrong");
$("#level-title").text("Game Over, Press Any Key to Restart");
startOver();
}
Having a timer is easy with setInterval, which, unlike setTimeout, will continue to execute the handler function with the specified delay until the interval is cleared.
If you wanted the value globally, you could do:
let seconds = 0
let timerInterval
function startTimer() {
timerInterval = setInterval(() => seconds++, 1000)
}
function resetTimer() {
seconds = 0
clearInterval(timerInterval)
}

how to put sleep function in javascript?

I am creating a game in html5 using javascript and I am having problem with sleep function. I want to hold off an isWin function for a few seconds before showing a popup declaring the person has won the game. here is part of the code.
modal: function (isWin) {
var bgDarker = this.game.make.bitmapData(this.game.width, this.game.height);
bgDarker.fill(50, 50, 50);
bgDarker = this.game.add.button(0, 0, bgDarker, function () { }, this);
bgDarker.tint = 0x000000;
bgDarker.alpha = 0.5;
var modalGroup = this.game.add.group();
var bg = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY - 40, (isWin ? "picWinPopup" : "picLostPopup"));
bg.scale.setTo(1);
bg.anchor.setTo(0.5);
modalGroup.add(bg);
var labelLevel2 = this.game.add.text(this.game.world.centerX + 100, this.game.world.centerY + 5, MatchingGame.indexImage, {
font: "48px " + MatchingGame.fontFaces[3],
fill: "#1a40ff",
boundsAlignH: "center",
boundsAlignV: "middle"
});
labelLevel2.anchor.setTo(0.5);
modalGroup.add(labelLevel2);
var labelTotalScore = this.game.add.text(this.game.world.centerX, this.game.world.centerY + 110, MatchingGame.score, {
font: "34px " + MatchingGame.fontFaces[3],
fill: "#ff2a5c",
boundsAlignH: "center",
boundsAlignV: "middle"
});
labelTotalScore.anchor.setTo(0.5);
modalGroup.add(labelTotalScore);
var btnReplay = this.makeButton("btnReplay", function (close) {
btnReplay.bgDarker.destroy();
btnReplay.modalGroup.destroy();
if(MatchingGame.indexImage==6){
MatchingGame.indexImage = 1;
}
this.game.stateTransition.to('Game');
this.imgLive1.visible = true;
this.imgLive2.visible = true;
this.imgLive3.visible = true;
MatchingGame.live = 3;
MatchingGame.levelscore = 0;
},this);
//btnReplay.anchor.setTo(0.5);
btnReplay.position.setTo(bg.position.x - 200, bg.position.y + 260)
btnReplay.bgDarker = bgDarker;
btnReplay.modalGroup = modalGroup;
modalGroup.add(btnReplay);
if (!isWin) {
var btnEnd = this.makeButton("btnEnd", function (close) {
btnEnd.bgDarker.destroy();
btnEnd.modalGroup.destroy();
this.imgLive1.visible = true;
this.imgLive2.visible = true;
this.imgLive3.visible = true;
MatchingGame.live = 3;
this.end();
},this);
btnEnd.position.setTo(bg.position.x + 200, bg.position.y + 260)
btnEnd.bgDarker = bgDarker;
btnEnd.modalGroup = modalGroup;
modalGroup.add(btnEnd);
}
else {
//setTimeout(3000);
//var TimeHandler = setTimeout(function(){clearTimeout(TimeHandler);},3000);
var btnNextLevel = this.makeButton("btnNextLevel", function (close) {
btnNextLevel.bgDarker.destroy();
btnNextLevel.modalGroup.destroy();
if(MatchingGame.indexImage==6){
MatchingGame.indexImage = 1;
} else {
MatchingGame.indexImage = MatchingGame.indexImage+1; }
this.game.stateTransition.to('Game');
this.imgLive1.visible = true;
this.imgLive2.visible = true;
this.imgLive3.visible = true;
MatchingGame.live = 3;
},this);
btnNextLevel.position.setTo(bg.position.x + 200, bg.position.y + 260)
btnNextLevel.bgDarker = bgDarker;
btnNextLevel.modalGroup = modalGroup;
modalGroup.add(btnNextLevel);
}
MatchingGame.live = 3;
this.game.add.tween(modalGroup).from({ y: -800 }, 600, Phaser.Easing.Bounce.Out, true);
this.game.world.bringToTop(modalGroup);
},
I did try to use sleep() and setTimeout() function but keep failing to implement it in javascript. can you help me solve this problem of putting a timer in javascript function? because I am having problem integrating setTimeout in javascript code that uses html5.
Use it like this
setTimeout(function() {
var btnNextLevel = this.makeButton("btnNextLevel", function (close) {
btnNextLevel.bgDarker.destroy();
btnNextLevel.modalGroup.destroy();
if(MatchingGame.indexImage==6){
MatchingGame.indexImage = 1;
} else {
MatchingGame.indexImage = MatchingGame.indexImage+1; }
this.game.stateTransition.to('Game');
this.imgLive1.visible = true;
this.imgLive2.visible = true;
this.imgLive3.visible = true;
MatchingGame.live = 3;
},this);
btnNextLevel.position.setTo(bg.position.x + 200, bg.position.y + 260)
btnNextLevel.bgDarker = bgDarker;
btnNextLevel.modalGroup = modalGroup;
modalGroup.add(btnNextLevel); }, 3000 );
javascript is single thread, so there is no sleep/wait/stop.
you should never make that only single thread stop working.
if you want to delay some code, use setTimeout.
however the proper way to use setTimeout is:
setTimeout(myFunction, 40000);
that is an example.
see full details:
mdn setTimeout
This may fit to your requirement
var TimeHandler = setTimeout(function(){clearTimeout(TimeHandler);},3000);

How to implement codepen jquery script in wordpress?

I am trying to implement a fancy slider from codepen in wordpress. I have correctly added the script using the enqueue script method. I know I did it coorectly because it worked for a very small experiment I tried. Now the pen is: http://codepen.io/suez/pen/wMMgXp .
(function() {
var $$ = function(selector, context) {
var context = context || document;
var elements = context.querySelectorAll(selector);
return [].slice.call(elements);
};
function _fncSliderInit($slider, options) {
var prefix = ".fnc-";
var $slider = $slider;
var $slidesCont = $slider.querySelector(prefix + "slider__slides");
var $slides = $$(prefix + "slide", $slider);
var $controls = $$(prefix + "nav__control", $slider);
var $controlsBgs = $$(prefix + "nav__bg", $slider);
var $progressAS = $$(prefix + "nav__control-progress", $slider);
var numOfSlides = $slides.length;
var curSlide = 1;
var sliding = false;
var slidingAT = +parseFloat(getComputedStyle($slidesCont)["transition-duration"]) * 1000;
var slidingDelay = +parseFloat(getComputedStyle($slidesCont)["transition-delay"]) * 1000;
var autoSlidingActive = false;
var autoSlidingTO;
var autoSlidingDelay = 5000; // default autosliding delay value
var autoSlidingBlocked = false;
var $activeSlide;
var $activeControlsBg;
var $prevControl;
function setIDs() {
$slides.forEach(function($slide, index) {
$slide.classList.add("fnc-slide-" + (index + 1));
});
$controls.forEach(function($control, index) {
$control.setAttribute("data-slide", index + 1);
$control.classList.add("fnc-nav__control-" + (index + 1));
});
$controlsBgs.forEach(function($bg, index) {
$bg.classList.add("fnc-nav__bg-" + (index + 1));
});
};
setIDs();
function afterSlidingHandler() {
$slider.querySelector(".m--previous-slide").classList.remove("m--active-slide", "m--previous-slide");
$slider.querySelector(".m--previous-nav-bg").classList.remove("m--active-nav-bg", "m--previous-nav-bg");
$activeSlide.classList.remove("m--before-sliding");
$activeControlsBg.classList.remove("m--nav-bg-before");
$prevControl.classList.remove("m--prev-control");
$prevControl.classList.add("m--reset-progress");
var triggerLayout = $prevControl.offsetTop;
$prevControl.classList.remove("m--reset-progress");
sliding = false;
var layoutTrigger = $slider.offsetTop;
if (autoSlidingActive && !autoSlidingBlocked) {
setAutoslidingTO();
}
};
function performSliding(slideID) {
if (sliding) return;
sliding = true;
window.clearTimeout(autoSlidingTO);
curSlide = slideID;
$prevControl = $slider.querySelector(".m--active-control");
$prevControl.classList.remove("m--active-control");
$prevControl.classList.add("m--prev-control");
$slider.querySelector(prefix + "nav__control-" + slideID).classList.add("m--active-control");
$activeSlide = $slider.querySelector(prefix + "slide-" + slideID);
$activeControlsBg = $slider.querySelector(prefix + "nav__bg-" + slideID);
$slider.querySelector(".m--active-slide").classList.add("m--previous-slide");
$slider.querySelector(".m--active-nav-bg").classList.add("m--previous-nav-bg");
$activeSlide.classList.add("m--before-sliding");
$activeControlsBg.classList.add("m--nav-bg-before");
var layoutTrigger = $activeSlide.offsetTop;
$activeSlide.classList.add("m--active-slide");
$activeControlsBg.classList.add("m--active-nav-bg");
setTimeout(afterSlidingHandler, slidingAT + slidingDelay);
};
function controlClickHandler() {
if (sliding) return;
if (this.classList.contains("m--active-control")) return;
if (options.blockASafterClick) {
autoSlidingBlocked = true;
$slider.classList.add("m--autosliding-blocked");
}
var slideID = +this.getAttribute("data-slide");
performSliding(slideID);
};
$controls.forEach(function($control) {
$control.addEventListener("click", controlClickHandler);
});
function setAutoslidingTO() {
window.clearTimeout(autoSlidingTO);
var delay = +options.autoSlidingDelay || autoSlidingDelay;
curSlide++;
if (curSlide > numOfSlides) curSlide = 1;
autoSlidingTO = setTimeout(function() {
performSliding(curSlide);
}, delay);
};
if (options.autoSliding || +options.autoSlidingDelay > 0) {
if (options.autoSliding === false) return;
autoSlidingActive = true;
setAutoslidingTO();
$slider.classList.add("m--with-autosliding");
var triggerLayout = $slider.offsetTop;
var delay = +options.autoSlidingDelay || autoSlidingDelay;
delay += slidingDelay + slidingAT;
$progressAS.forEach(function($progress) {
$progress.style.transition = "transform " + (delay / 1000) + "s";
});
}
$slider.querySelector(".fnc-nav__control:first-child").classList.add("m--active-control");
};
var fncSlider = function(sliderSelector, options) {
var $sliders = $$(sliderSelector);
$sliders.forEach(function($slider) {
_fncSliderInit($slider, options);
});
};
window.fncSlider = fncSlider;
}());
/* not part of the slider scripts */
/* Slider initialization
options:
autoSliding - boolean
autoSlidingDelay - delay in ms. If audoSliding is on and no value provided, default value is 5000
blockASafterClick - boolean. If user clicked any sliding control, autosliding won't start again
*/
fncSlider(".example-slider", {autoSlidingDelay: 4000});
var $demoCont = document.querySelector(".demo-cont");
[].slice.call(document.querySelectorAll(".fnc-slide__action-btn")).forEach(function($btn) {
$btn.addEventListener("click", function() {
$demoCont.classList.toggle("credits-active");
});
});
document.querySelector(".demo-cont__credits-close").addEventListener("click", function() {
$demoCont.classList.remove("credits-active");
});
document.querySelector(".js-activate-global-blending").addEventListener("click", function() {
document.querySelector(".example-slider").classList.toggle("m--global-blending-active");
});
The javascript code can e found above and in the mentioned link.I know that in wordpress we have to use jQuery in place of $ but I still can't seem to figure out how to do it in this case. And one more thing, the css is in scass form but I have taken the compiled css form but I don't think that is causing any problem (rignt?) Everything I have tried till this point has failed. Any help will be appreciated
You can use $ instead of jQuery in WordPress so long as you wrap all your code inside the following:
(function($) {
// Your code goes here
})( jQuery );
If the code is in the header (before the document is ready) then instead use:
jQuery(document).ready(function( $ ) {
// Your code goes here
});
If your code is still having problems, then please include both the enqueue code in your theme and the error messages

Image not switching on hover

Trying to get this image to scroll through images on hover but its not work. Live demo at: http://codepen.io/bskousen/pen/Ksphr
Using jquery
script:
$(document).ready(function() {
$('.imageBox').hover(startScroll, stopScroll);
});
var scrollInterval;
var i = 2;
function startScroll() {
scrollInterval = setInterval(scrollImages(this), 100);
}
function stopScroll() {
i = 2;
$(this).children('img').fadeOut();
$(this).children('img:nth-child(1)').fadeIn();
clearInterval(scrollInterval);
}
function scrollImages(x) {
$('#count').append('running' + i + ' ');
var imageCount = $(x).children('img').length;
$(x).children('img').fadeOut();
$(x).children('img:nth-child(' + i + ')').fadeIn();
if (i == imageCount) {
i = 2;
}
else {
i++;
}
}
The setInterval is not formatted correctly. Try this:
function startScroll() {
me = this;
scrollInterval = setInterval(function(){
scrollImages(me);
}, 100);
}

Background image slideshow transition issue

I need help in improving the script for my background image slideshow.
I managed to create a fade in effect with .fadeIn(600) JS function. But, I want the images to switch between each other, not between white background.
In other words, I need to smooth up the transition between images.
Note that each image has a caption, but I'm OK with it as it is. I don't need any transitions for text.
JSFiddle http://jsfiddle.net/newsha/B4TXj/
var timer;
$(document).ready(function () {
// background image on load
var numberImages = 4
var images = [];
for (var i = 1; i <= numberImages; i++) {
images.push(i);
}
var imgValue = 1
$('.backgroundImage').addClass('bg' + imgValue + '');
// Switch background image - forwards
$('.imgSwitchRight').click(function () {
$('.backgroundImage').each(function (e) {
$(this).removeClass('bg1 bg2 bg3 bg4').fadeOut(0);
});
clearTimeout(timer);
timer = setTimeout(function () {
$('.imgSwitchRight').click();
}, 8000);
if (imgValue < numberImages) {
imgValue++
} else {
imgValue = 1
}
$('.backgroundImage').addClass('bg' + imgValue + '').fadeIn(600);
});
clearTimeout(timer);
timer = setTimeout(function () {
$('.imgSwitchRight').click();
}, 8000);
// Switch background - backwards
$('.imgSwitchLeft').click(function () {
$('.backgroundImage').each(function (e) {
$(this).removeClass('bg1 bg2 bg3 bg4').fadeOut(0);
});
clearTimeout(timer);
timer = setTimeout(function () {
$('.imgSwitchRight').click();
}, 8000);
if (imgValue > 1) {
imgValue--
} else {
imgValue = numberImages
}
$('.backgroundImage').addClass('bg' + imgValue + '').fadeIn(600);
});
clearTimeout(timer);
timer = setTimeout(function () {
$('.imgSwitchRight').click();
}, 8000);
});
I just used a secound div aas a swapping plane. the visible div is now fading out while the invisible one is fading in. after that the roles are switched and it goes on and on.. one problem still remains. if switching the images too fast the classes "stack" because the animation of the fading div is interrupted and the class will not be removed.. Problem solved..
var timer;
$(document).ready(function () {
// background image on load
var numberImages = 5,
easetime = 2000,
changetimeout = 5000;
var images = [];
for (var i = 1; i <= numberImages; i++) {
images.push(i);
}
var imgValue = 1;
var visibleBackground = $('.backgroundImage.a');
var invisibleBackground = $('.backgroundImage.b');
$('.backgroundImage').hide();
visibleBackground.addClass('bg' + imgValue + '').show();
var dir = 1;
function changeBG(){
oldValue = imgValue;
imgValue = (imgValue+dir)%numberImages;
$('.rotating-text'+imgValue).fadeIn(easetime);
$('.rotating-text'+oldValue).fadeOut(easetime);
clearTimeout(timer);
timer = setTimeout(function () {
changeBG();
}, changetimeout);
visibleBackground.fadeOut(easetime);
setTimeout(function(){
var tmpBackground = visibleBackground, tmpVal = oldValue;
return function(){
tmpBackground.removeClass('bg' + tmpVal)
}
}(), easetime);
invisibleBackground.addClass('bg' + imgValue + '').fadeIn(easetime);
var swap = visibleBackground;
visibleBackground = invisibleBackground;
invisibleBackground = swap;
}
// Switch background image - forwards
$('.imgSwitchRight').click(function () {
dir = 1;
changeBG()
});
// Switch background - backwards
$('.imgSwitchLeft').click(function () {
dir = -1;
changeBG()
});
timer = setTimeout(function () {
changeBG();
}, changetimeout);
});
http://jsfiddle.net/B4TXj/11/

Categories