And thanks for stopping by.
I've been trying to add a feature, or function, to a project that I'm working on, but I just can't wrap my head around it.
When my project loads I want the user to activate the time as soon as they move, or click, one of the orbs -- not as soon as the project loads. I know there's an onClick or click event, but I'm having trouble implementing it on the js code. I've gone as far as commenting-out or "greying" entire functions to test things out.
Here's some of the time code:
function clockStart() {
numberOfSecs = setInterval(function () {
seconds.text(`${second}`)
second = second + 1
}, 1000);
}
function rewindSec(seconds) {
if (seconds) {
clearInterval(seconds);
}
}
gameStart();
// GAMES BEGIN!!!
function gameStart() {
var cards = shuffle(listOfCards);
deckOfCards.empty();
match = 0;
Moves = 0;
moveNum.text("0");
ratingStars.removeClass("fa-angry").addClass("fa-star");
for (var i = 0; i < cards.length; i++) {
deckOfCards.append($('<li class="card"><i class="fab fa-' + cards[i] + '"></i></li>'))
}
sourceCard();
rewindSec(numberOfSecs);
second = 0;
seconds.text(`${second}`)
clockStart();
};
Here's a link to the project that I'm talking about:
Full Page View: https://codepen.io/idSolomon/full/RYPZNp/
Editor View: https://codepen.io/idSolomon/pen/RYPZNp/?editors=0010
WARNING: Project not mobile-friendly. At least not yet.
If someone can help me out with this, a thousand thank yous will come your way.
Thanks!
You can Change the event of starting the clock at another position
First remove the clockStart() function from the gameStart() method
seconds.text(`${second}`)
//clockStart();
if have added an Extra variable to detect if the clock is started or not
var isClockStarted=false;
The following code will start the timer when a card is clicked:
var sourceCard = function () {
deckOfCards.find(".card").bind("click", function () {
if(!isClockStarted)
clockStart();
The Bellow Code will check if the timer is started or not.
function clockStart() {
if(!isClockStarted){
isClockStarted=true;
numberOfSecs = setInterval(function () {
seconds.text(`${second}`)
second = second + 1
}, 1000);
}
}
I have found that you are not stopping the timer even after the game finishes
If canceled a game it starts timer again //toCheck
Related
I am trying to automatic user logout after inactivity of 5 mins without any dependencies or modules using javascript but it works fine on first page of my Angular but not working on the other routers, on other routers it kept showing alertbox even after click ok. also if i switch one page(router) to another it still counts the countdown of last page rather then resetting it and counting for new page.
Here is my code -
var IDLE_TIMEOUT = 10; //seconds
var _idleSecondsCounter = 0;
document.onclick = function () {
_idleSecondsCounter = 0;
};
document.onmousemove = function () {
_idleSecondsCounter = 0;
};
document.onkeypress = function () {
_idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 5000);
function CheckIdleTime() {
_idleSecondsCounter++;
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
alert("Time expired! Please Login Again");
localStorage.clear();
window.location.replace(location.origin);
}
}
it kept showing even after click if i write above code on other pages also, What should i try now?
You need to determine the right place where this particular logic should be placed.
1.) Logic for the view: Logics that are applicable only for a particular view should remain in that same component.
2.) Reused Logic: Based on your problem statement you should form a service for this particular scenario. Add this logic to that service and reuse it on every single view by injecting this service into each of the view's .ts file.
Go with the second option(Reused Logic), this might work as expected.
I got X DIV (TopRowRight1, TopRowRight2, TopRowRight3...) , each containing a different Google Geochart generated by a php page : GeochartPerProvince.php?template=X.
function getResult(template){
jQuery.post("GeochartPerProvince.php?template="+template,function( data ) {
jQuery("#TopRowRight"+template).html(data);
});
}
jQuery().ready(function(){
getResult(1);
setInterval("getResult(1)",10000);
getResult(2);
setInterval("getResult(2)",10000);
getResult(3);
setInterval("getResult(3)",10000);
});
jQuery(function () {
var $els = $('div[id^=TopRowRight]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 5000)
});
Every 5 seconds, i fade out one and fade in the next one. This works perfectly.
For now, the php page in the DIV is refreshed every 10 seconds. This works too.
But what i dream about is that the php page in the DIV is reloaded AFTER the DIV is faded out instead of every 10 seconds. How to do it?
Solved. How it works properly:
function getResult(template){
jQuery.post("GeochartPerProvince.php?template="+template,function( data ) {
jQuery("#TopRowRight"+template).html(data);
});
}
$(document).ready(function(){
getResult(0);
getResult(1);
getResult(2);
//setInterval("getResult(2)",10000); <== keep this piece of code in case of need.
});
$(document).ready(function () {
var $els = $('div[id^=TopRowRight]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
getResult(i);
$els.eq(i).fadeIn();
})
}, 10000)
});
You're already using a callback function after the element has been faded out. So why not call your getResult function inside it?
$el.fadeOut(function(){
// stuff
getResult(i)
})
I have a few suggestions and an example code for you to achieve what you need :
Use $ instead of jQuery for easier reading / writing
$(document).ready is the proper start point for dom related functions
If only one div is visible at a time, do not use too many divs. Most of the time one div is enough for alternating / refreshing content. If there is in/out animation or cross-fading, two divs would be needed. (Example below uses two divs)
Avoid using setInterval except you really really need. Logics with setTimeout better handles unexpected delays such $.post may cause.
start with html code something like this:
...
<div class="top-row-right" style="display:block"></div>
<div class="top-row-right" style="display:none"></div>
...
js:
$(document).ready( function() {
var len = 4; // 'I got X DIV..' This is where we put the value of X.
var template = -1;
function refreshChart() {
template = (template + 1) % len;
$.post("GeochartPerProvince.php?template="+template, function(data) {
var offscreenDiv = ('.top-row-right:hidden');
var onscreenDiv = ('.top-row-right:visible');
offScreenDiv.html(data);
onScreenDiv.fadeOut('slow', function() {
offScreenDiv.fadeIn();
setTimeout(refreshChart, 10000);
});
});
}
refreshChart();
});
I have a little problem with my code.
I have it setup so that by default, a rotating fadeIn fadeOut slider is auto playing, and when a user clicks on a li, it will jump to that 'slide' and pause the slider for x amount of time.
The problem i have is that if the user clicks on multiple li's very fast, then it will run color1() multiple times with will start colorInterval multiple times. This gives a undesired effect.
So what i need help with, is figuring out how to reset my code each time a li is clicked, so whenever ColorClick is clicked, i want to make sure that there are no other instances of colorInterval before i start a new one.
Thanks in advance!
=================================
edit:
I now have another problem, i believe that i fixed the clearInterval problem, but now if you look at var reset, you'll see that it runs color1() each time a li is clicked, which runs multiple intervals, so i need to delete the previous instance of color1() each time it is called, to make sure that it doesnt repeat any code inside multiple times. So when a li is clicked delete any instances of color1()
or
i need that instead of running color1 in var reset, i will go straight to colorInterval instead of running color1() for each li clicked,
so run colorInterval after x amount of time in var reset.
function color1() {
var pass = 0;
var counter = 2;
var animationSpeed = 500;
var $colorContent = '.color-container-1 .color-content-container'
var $li = '.color-container-1 .main-color-container li'
$($li).on('click', function() {
colorClick($(this));
});
function colorClick($this) {
var $getClass = $this.attr("class").split(' ');
var $whichNumber = $getClass[0].substr(-1);
var $Parent = '.color-container-1 ';
pass = 1;
$($colorContent).fadeOut(0);
$($colorContent + '-' + $whichNumber).fadeIn(animationSpeed);
var reset = setTimeout(function() {
clearTimeout(reset);
pass = 0;
color1();
}, 10000);
}
var colorInterval = setInterval(function() {
if (pass > 0) {
clearInterval(colorInterval);
return; //stop here so that it doesn't continue to execute below code
}
$($colorContent).fadeOut(0);
$(($colorContent + '-' + counter)).fadeIn(animationSpeed);
++counter
if (counter === $($colorContent).length + 1) {
counter = 1;
}
}, 7000);
}
You could just clear the interval inside of the click event.
var colorInterval;
$($li).on('click', function() {
clearInterval(colorInterval);
colorClick($(this));
});
//Your other code
colorInterval = setInterval(function() {
//Rest of your code
});
One thing play with is jQuery animations have a pseudo class selector :animated when animation is in progress
if(!$('.your-slide-class:animated').length){
// do next animation
}
This is the entire function I am working on:
function collapse(){
var i = 0;
var currColors = [];
var currTitles = [];
// Get the color and the course id of all the current courses
$('.course').each(function (){
if (rgb2hex($(this).css("background-color")) !== "#f9f9f9") {
currColors.push(rgb2hex($(this).css("background-color")));
currTitles.push($(this).children(".course-id").text());
$(this).children(".course-delete").remove();
$(this).children(".course-id").text("");
$(this).css('background', "#f9f9f9");
}
});
alert("made it");
// Redistribute the classes
// This is where reverse lookup will eventually happen
i = 0;
$('div.course').each(function (){
if (i>=currTitles.length){
return false;
}
$(this).children(".course-id").text(currTitles[i]);
$(this).css('background', currColors[i++]);
$(this).append("<button id='temp' class='course-delete'>X</button>");
});
var i = currColors.length-1;
};
And this is the problematic section
$('.course').each(function (){
if (rgb2hex($(this).css("background-color")) !== "#f9f9f9") {
currColors.push(rgb2hex($(this).css("background-color")));
currTitles.push($(this).children(".course-id").text());
$(this).children(".course-delete").remove();
$(this).children(".course-id").text("");
$(this).css('background', "#f9f9f9");
}
});
I have this function collapse that is supposed to fill in the blank spot in a list of divs that the user has been adding to the screen if they delete one. This function was working fine at one point, but obviously I have screwed it up some how.
There are only and always will be 6 '.course' items because that is the size of the list. When collapse() is called it stops running after n times where n is the number of '.course' elements currently in use. The loop stops there and the whole function stops there. I have tried putting alert() statements everywhere but still no luck. If someone spots what I am missing I would really appreciate it.
I have figured out a work around for now, but I would like to know why my entire function is crashing in the middle.
My code below needs to put in a setInterval within a for loop. I basically need to put in a 10 second pause between the next iteration of the for loop. This is for a very basic script which shows banners in a div for 10 seconds before moving onto the next one. It existing setInterval is code I got off another website as I ran out of options. Any help? And if you don't mind explaining the logic to me so that I know for the future :)
$("document").ready(function() {
// bannerChange
function bannerChange(banner,div,milliseconds) {
var length = banner.length;
for(i=0;i<length;i++) {
(function(i) {
setInterval(function() {
var url = banners[i].url;
var img = banners[i].image;
$("#"+div).html("<a href='"+url+"' target='_Blank'><img src='www/images/banners/"+img+"' /></a>");
},milliseconds)
})(i);
}
}
function showBanner(bannerName, bannerDiv, milliseconds) {
var url = "www/scripts/ajax/getBanners.php";
$.post(url, {name: bannerName}, function(data) {
if(data.response == true) {
bannerChange(data.banners,bannerDiv,milliseconds);
}
});
}
// Run banners
showBanner("Test Banner","test",10000);
});
Here's an updated version based on the comment:
// Start by getting the banners:
var banners = [];
var currentBanner;
function getBannersFromServer(...) {
// TODO: make ajax call to server for banners
// push the banners into a queue for later
for (var i in bannerFromServer) {
banners.push(bannersFromServer[i]);
}
}
// Then run through them:
function showNextBanner() {
// advance to next banner
currentBanner++
// go back to the beginning after the last banner is displayed
if(currentBanner >= banners.length) currentBanner = 0;
// pull a banner out of the queue
var banner = banners[currentBanner];
// TODO: Show the banner in the div
// do it again in 10 seconds
showNextBanner();
}
// start it all
getBannersFromServer();
getNextBanner();
Try using:
.delay()
Here is a great example of this function in use!
Try this
var i=0;//Global Variable
function bannerChange(banner, div, milliseconds) {
var length = banner.length;
setInterval(function() {
var url = banners[i].url;
var img = banners[i].image;
$("#"+div).html("<a href='"+url+"' target='_Blank'><img src='www/images/banners/"+img+"' /></a>");
i++;
if(i >= length) i=0;//To reiterate from first
},milliseconds);
}
Hope this solves your problem.