Progress bar not resetting - javascript

I'm creating a countdown of 10 seconds, and at the end, some functions triggers.
These functions that recall the countdown function to start again. However, when it's called again, the bar is still full, resulting in a loop.
Here's the countdown function.
function LoadTime() {
firebase.auth().onAuthStateChanged(User => {
if(User) {
var RemainTime = 10;
var DownTime = setInterval(function(){
document.getElementById("progressBar").value = 10 - --RemainTime;
if(RemainTime <= 0)
clearInterval(DownTime);
if (RemainTime == 0){
storewager();
if (Roulette.bet == 1) {
RouOutcome();
}
else {
LoadTime();
}
}
},1000);
} else {
alert("please login");
}
});
}
I want this functions to reset the progress bar each time it's triggered. Been stuck on this for a while, so any help is much appreciated.
EDIT:
Here's the tree of the functions.
Page load --> LoadTime --> (end of countdown) --> (Outcome process) --> RouOutcome() --> LoadTime().
Seems to be when LoadTime is triggered when it's already finished once, it seems to run the process multiple times. It may be to do with the alert boxes causing issues for the countdown.
Been stuck on this for hours, so any help is much appreciated.
EDIT 2:
Here's are the relevant functions in the correct order. This is assuming the users picks a bet option, and enters a bet. I'm trying to create roulette. Is it possible that the issue could be with the alerts?
function LoadTime() {
Roulette.load = 1;
CoinFlip.load = 0;
document.getElementById().style.visibility = "hidden";
firebase.auth().onAuthStateChanged(User => {
if(User) {
console.log("user is logged in");
Roulette.choice = 0;
var RemainTime = 15;
var DownTime = setInterval(function(){
document.getElementById("progressBar").value = 15 - --RemainTime;
if(RemainTime <= 0)
clearInterval(DownTime);
if (RemainTime == 0){
storewager();
if (Roulette.bet == 1) {
RouOutcome();
}
else {
LoadTime();
}
}
},1000);
} else {
alert("please login");
}
});
}
function storewager(){
var UserID = firebase.auth().currentUser.uid;
firebase.database().ref("Users").child(UserID).child("coinbet").set(0);
var coinwager = document.getElementById("coininput").value;
if (coinwager > 0) {
Roulette.bet = 1;
var balref = firebase.database().ref("Users").child(UserID).child("coinbet");
firebase.database().ref("Users").child(UserID).child("coinbet").set(coinwager);
var coinref = firebase.database().ref();
coinref.child("coinbet").set(coinwager);
BalVer();
}
else {
alert("No bet was placed");
Roulette.bet = 0;
LoadTime();
}
}
function BalVer(){
var UserID = firebase.auth().currentUser.uid;
var dbRoot = firebase.database().ref("Users").child(UserID);
dbRoot.once("value", snap => {
var cData = snap.val();
var cBet = cData.coinbet;
var uBal = cData.userbalance;
var BalUp = uBal-cBet;
if (BalUp < 0) {
alert("You do not have enough balance")
var BetWipe = firebase.database().ref("Users").child(UserID).child("coinbet").set(0);
}
else {
changeuserbal();
}
});
}
function changeuserbal(coinwager){
var UserID = firebase.auth().currentUser.uid;
var dbRoot = firebase.database().ref("Users").child(UserID);
dbRoot.once("value", snap => {
var cData = snap.val();
var cBet = cData.coinbet;
var uBal = cData.userbalance;
var BalUp = uBal-cBet;
firebase.database().ref("Users").child(UserID).child("userbalance").set(BalUp);
if (CoinFlip.load == 1) {
CoinOutcome();
}
else {
RouOutcome();
}
});
}
function RouOutcome(UserID) {
var OutCome = 0 + (Math.random() * 10000);
var UserID = firebase.auth().currentUser.uid;
if (OutCome <= 10000) {
if (Roulette.choice == 1) {
alert("You won");
var dbRoot = firebase.database().ref("Users").child(UserID);
dbRoot.once("value", snap => {
var cData = snap.val();
var cBet = cData.coinbet;
var uBal = cData.userbalance;
var WinBal = cBet * 2 + uBal
var NewBal = firebase.database().ref("Users").child(UserID).child("userbalance").set(WinBal);
//UpdateBal();
Roulette.comp = 1;
LoadTime();
});
}
else {
alert("you lost/didn't place bet");
Roulette.comp = 1;
LoadTime();
}
}
else if ((OutCome >= 4738) && (OutCome <=9474)) {
var UserID = firebase.auth().currentUser.uid;
if (Roulette.choice == 2) {
alert("You won");
var dbRoot = firebase.database().ref("Users").child(UserID);
dbRoot.once("value", snap => {
var cData = snap.val();
var cBet = cData.coinbet;
var uBal = cData.userbalance;
var WinBal = cBet*2+uBal
var NewBal = firebase.database().ref("Users").child(UserID).child("userbalance").set(WinBal);
//UpdateBal();
LoadTime();
});
}
else {
alert("you lost/didn't place bet");
LoadTime();
}
}
else {
var UserID = firebase.auth().currentUser.uid;
if (Roulette.choice == 3) {
alert("You won");
var dbRoot = firebase.database().ref("Users").child(UserID);
dbRoot.once("value", snap => {
var cData = snap.val();
var cBet = cData.coinbet;
var uBal = cData.userbalance;
var WinBal = cBet*14+uBal
var NewBal = firebase.database().ref("Users").child(UserID).child("userbalance").set(WinBal);
//UpdateBal();
LoadTime();
});
}
else {
alert("you lost/didn't place bet");
LoadTime();
}
}
}
Thanks very much for your help, if you need any more info please say.

Here is an example I created for you to follow. You don't show you attempt at resetting the bar so this is the best I can do at explaining for now.
var pBar = document.getElementById("progressBar");
var pText = document.getElementById("progressText");
startTimer();
function startTimer() {
var downIncrement = 10;
var DownTime = setInterval(function() {
var currentValue = pBar.getAttribute("aria-valuenow");
var newValue = currentValue - downIncrement;
pBar.setAttribute("aria-valuenow", newValue);
pBar.style = "width:" + newValue + "%";
pText.textContent = newValue / 10;
if (newValue <= 0) {
console.log("time is up!");
clearInterval(DownTime);
var Roulette = storewager();
if (Roulette.bet == 1) {
RouOutcome();
} else {
LoadTime();
}
}
},
1000);
}
function storewager() {
console.log("done with store wager");
return {
bet: 1
};
}
function RouOutcome() {
console.log("done with RouOutcome");
// restart progress bar
LoadTime();
}
function LoadTime() {
pBar.setAttribute("aria-valuenow", 100);
pBar.style = "width: 100%";
pText.textContent = "10";
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="progress">
<div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width:100%">
<span id="progressText">10</span>
</div>
</div>

Related

Have to call alert for rest JS to run on Iphone (safari)

I'm having trouble with JS code not executing on iPhone if I don't call alert before if statement. This is my code:
submitHandler = (e) => {
e.preventDefault();
var dataFromForm = $("#send").serialize();
alert(); // Without this the code below wont execute on iphne
if (window.localStorage) {
if (localStorage.getItem("timeout")) {
const timePrev = localStorage.getItem("timeout");
const timeNow = Math.round(new Date().getTime() / 1000);
if (timeNow - timePrev >= 300) {
var available = true;
} else {
var available = false;
document.getElementById("message").innerHTML =
'<span class="fail"> Spam protection</span>';
}
} else {
var available = true;
}
} else {
var available = true;
}
if (available) {
$.post("mail.php", dataFromForm, function (data) {
document.getElementById("message").innerHTML = "";
console.log(data);
data = JSON.parse(data);
console.log(data);
if (data.statusBool === true) {
document.getElementById("message").innerHTML =
'<span class="success">' + data.status + "</span>";
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementById("msg").value = "";
var timenow = Math.round(new Date().getTime() / 1000);
localStorage.setItem("timeout", timenow);
} else {
document.getElementById("message").innerHTML =
'<span class="fail">' + data.status + "</span>";
}
});
}
setTimeout(function () {
document.getElementById("message").innerHTML = "";
}, 3000);
};
code below alert doesn't execute if I don't put alert before that statement.
Does anyone know how to solve this, or have an idea of what could I use instead of alert, so it's not visible for the user?
Answer by #Chris G
jsfiddle.net/rqht1kzo
localStorage.setItem('timeout', new Date().getTime() / 1000 - 400);
var available = false;
const timePrev = window.localStorage && window.localStorage.getItem('timeout');
if (timePrev) {
const timeNow = Math.round(new Date().getTime() / 1000);
if (timeNow - timePrev >= 300) available = true;
}
if (available) {
console.log("it's available")
} else {
document.getElementById('message').innerHTML = '<span class="fail"> fail message</span>';
}

Cannot get content of div to store locally and load locally

I have a JS function to save and load content of a notepad I've made, locally.
I tried to replicate this for a div which contains times of a stopwatch.(see code below)
The stopwatch when paused will write it's time to this div to be saved, I want these times to save when I refresh / close and reopen the page.
It works for my notes in the notepad, please can someone explain where I'm going wrong?
JavaScript for save function:
//Storage of Text-Box
const notesInput = document.querySelector('#notes');
function remFunc() {
// store the entered name in web storage
localStorage.setItem('notes', notes.value);
}
function loadfunc() {
if(localStorage.getItem('notes')) {
let notes_var = localStorage.getItem('notes');
notes.value= notes_var;
} else {
}
}
document.body.onload = loadfunc();
//Storage of Times DIV
const output = document.querySelector('#output');
function remfunc2() {
localStorage.setItem('output', outContent.innerHTML);
}
function loadfunc2() {
if(localStorage.getItem('output')) {
let output_var = localStorage.getItem('output');
output.innerHTML = output_var ;
} else {
}
}
document.body.onload = loadfunc2();
This is the div:
<div id="output" name="output" class="buttonZ logPad"></div>
Here is the stopwatch Javascript:
// Timer JS
var flagclock = 0;
var flagstop = 0;
var stoptime = 0;
var splitcounter = 0;
var currenttime;
var splitdate = '';
var output;
var clock;
function startstop()
{
var startstop = document.getElementById('startstopbutton');
var startdate = new Date();
var starttime = startdate.getTime();
if(flagclock==0)
{
startstop.value = 'Stop';
flagclock = 1;
counter(starttime);
}
else
{
startstop.value = 'Start';
flagclock = 0;
flagstop = 1;
splitdate = '';
logTime();
}
}
function counter(starttime)
{
output = document.getElementById('output');
clock = document.getElementById('clock');
currenttime = new Date();
var timediff = currenttime.getTime() - starttime;
if(flagstop == 1)
{
timediff = timediff + stoptime
}
if(flagclock == 1)
{
clock.innerHTML = formattime(timediff,'');
clock.setAttribute('value', formattime(timediff, ''));
refresh = setTimeout('counter(' + starttime + ');',10);
}
else
{
window.clearTimeout(refresh);
stoptime = timediff;
}
}
function formattime(rawtime,roundtype)
{
if(roundtype == 'round')
{
var ds = Math.round(rawtime/100) + '';
}
else
{
var ds = Math.floor(rawtime/100) + '';
}
var sec = Math.floor(rawtime/1000);
var min = Math.floor(rawtime/60000);
ds = ds.charAt(ds.length - 1);
if(min >= 60)
{
startstop();
}
sec = sec - 60 * min + '';
if(sec.charAt(sec.length - 2) != '')
{
sec = sec.charAt(sec.length - 2) + sec.charAt(sec.length - 1);
}
else
{
sec = 0 + sec.charAt(sec.length - 1);
}
min = min + '';
if(min.charAt(min.length - 2) != '')
{
min = min.charAt(min.length - 2)+min.charAt(min.length - 1);
}
else
{
min = 0 + min.charAt(min.length - 1);
}
return min + ':' + sec + ':' + ds;
}
function resetclock()
{
flagstop = 0;
stoptime = 0;
splitdate = '';
window.clearTimeout(refresh);
if(flagclock !== 0) {
startstopbutton.value = 'Start';
flagclock = 0;
flagstop = 1;
splitdate = '';
}
if(flagclock == 1)
{
var resetdate = new Date();
var resettime = resetdate.getTime();
counter(resettime);
}
else
{
clock.innerHTML = "00:00:0";
}
}
//Split function
function splittime()
{
if(flagclock == 1)
{
if(splitdate != '')
{
var splitold = splitdate.split(':');
var splitnow = clock.innerHTML.split(':');
var numbers = new Array();
var i = 0
for(i;i<splitold.length;i++)
{
numbers[i] = new Array();
numbers[i][0] = splitold[i]*1;
numbers[i][1] = splitnow[i]*1;
}
if(numbers[1][1] < numbers[1][0])
{
numbers[1][1] += 60;
numbers[0][1] -= 1;
}
if(numbers[2][1] < numbers[2][0])
{
numbers[2][1] += 10;
numbers[1][1] -= 1;
}
}
splitdate = clock.innerHTML;
output.innerHTML += (++splitcounter) + '. ' + clock.innerHTML + '\n';
}
}
function logTime() {
const time = document.getElementById('clock').getAttribute('value');
document.getElementById('output').innerHTML += (++splitcounter) + '. ' + time + '<br />';
}
function time() {
splittime();
resetclock();
}
Any help will be much appreciated! Thank you.
Okay, so I figured out what I was doing wrong.
The 'output' variable was being used in the timer code.
This prevented me from setting the variable correctly.
I changed the id for the div and the variable name i was using.
I ran this code in my console on this page and it is working:
let counter = 0;
const outContent = document.querySelector('#notify-container');
setInterval(function()
{
counter++;
outContent.innerHTML = `${counter*2} seconds`;
localStorage.setItem('output', outContent.innerHTML);
}, 2000);
function loadfunc2() {
if(localStorage.getItem('output')) {
let output_var = localStorage.getItem('output');
outContent.innerHTML = output_var ;
counter = parseInt(outContent.innerHTML.split(' ')[0], 10)
}
}
loadfunc2()
Paste it into the console, run it, leave it for a few seconds, then refresh the page, paste it and run it again. You can see it working.

Javascript Timers assistance

I am having some issues trying to use the console to modify the time remaining on one site.
I want to be able to set the Time remaining to zero to be able to proceed to the next page.
I believe that the issue is that there are multiple things that need to be set in order to proceed to the next page.
See code below, any help you can provide would be appreciated.
var pageLoaded = 0;
var timerStatus = 'pending';
var secondsRemaining = -1;
var secondsElapsed = -1;
var startTicks = 0;
var errorCount = 0;
var estimatedSecondsRemaining = -1;
var zeroTimeCounter = 0;
var intervalIdUpdateBothTimers;
var nonLinearGuid = null;
$(document).ready(function() {
setInterval('AutoSave()', 120000);
intervalIdUpdateBothTimers = setInterval('UpdateBothTimers()', 1000);
if (timerStatus == 'pending') {
var totaltimeclock = document.getElementById('TotalTimeClock');
if (totaltimeclock != null) {
document.getElementById('TotalTimeClock').innerHTML = '-- \: -- \: --';
}
var timeremainingclock = document.getElementById('TimeRemainingClock');
if (timeremainingclock != null) {
document.getElementById('TimeRemainingClock').innerHTML = '-- \: -- \: --';
}
StartTimer();
}
});
function loaded(i,f) {
if (document.getElementById && document.getElementById(i) != null)
{
f();
}
else if (!pageLoaded) setTimeout('loaded(\''+i+'\','+f+')',100);
}
function SuspendTimer() {
UpdateBothTimers();
if (timerStatus == 'active') {
var data = "s=2&cp=" + this.location.pathname + "&nlg=" + GetNonLinearGuid();
timerStatus = 'suspended';
$.ajax({
type: "POST",
url: "/Courses/ajax/CourseData.aspx",
data: data,
success: displayTime,
async: false
});
clearInterval(intervalIdUpdateBothTimers);
}
}
function AutoSave()
{
if (timerStatus == 'active')
{
SaveTime();
}
}
function SaveTime()
{
var data = '';
if (typeof window.IsScormPage === 'undefined')
{
data = "cp=" + this.location.pathname + "&sp=false";
}
else
{
data = "cp=" + this.location.pathname + "&sp=true";
}
data += "&nlg=" + GetNonLinearGuid();
$.ajax({
type: "POST",
url: "/Courses/ajax/CourseData.aspx",
data: data,
success: displayTime,
async: false
});
}
function StartTimer()
{
timerStatus = 'active';
SetNonLinearGuid();
SaveTime();
}
// Sets the nonLinearGuid with the one in the DOM
// the GUID was generated in the server side and
// passed it to the client side (DOM)
function SetNonLinearGuid()
{
var $nonLinearGuid = $("#nonLinearGuid");
if ($nonLinearGuid === undefined)
{
$nonLinearGuid = $("input[name=nonLinearGuid]");
}
if ($nonLinearGuid.length)
{
nonLinearGuid = $nonLinearGuid.val() || null;
window.nonLinearGuid = window.nonLinearGuid || nonLinearGuid;
}
}
function GetNonLinearGuid() {
var nlg = (window.NonLinearGuid || nonLinearGuid),
admin = getQueryStringByName("admin", parent.window.location.href) || "";
if (admin.toLowerCase() == "d3v") {
printNonLinearGuid(nlg);
}
return nlg;
}
function getQueryStringByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
function displayTime(result)
{
if (result.isOk == false)
{
alert(result.message);
}
else
{
var d = new Date();
startTicks = d.getTime();
secondsRemaining = parseInt($(result).find("SecondsRemaining").text());
secondsElapsed = parseInt($(result).find("SecondsElapsed").text());
redirectUrl = $(result).find("RedirectUrl").text();
var suspendTimer = $(result).find("SuspendTimer").text();
var dataNonLinearGuid = "?nlg=" + GetNonLinearGuid();
if (redirectUrl != "") {
location.href = redirectUrl;
}
isError = $(result).find("Error").text();
if (isError == "true")
{
errorCount++;
if (errorCount > 3)
{
logout();
}
}
isOverworked = $(result).find("IsOverworked").text();
if (isOverworked == "true")
{
location.href = "/Courses/MyAccountNonLinear.aspx" + dataNonLinearGuid;
}
if (suspendTimer.length > 0) {
if ($.trim(suspendTimer).toLowerCase() == "true") {
SuspendTimer();
}
}
}
}
function logout()
{
window.top.location.href = "/Courses/loggedout.aspx";
}
function UpdateBothTimers() {
if (timerStatus != 'active') return;
if (secondsElapsed >= 0)
{
UpdateElapsedTimer();
//secondsElapsed++;
}
if (secondsRemaining >= 0) {
UpdateRemainingTimer();
}
if (estimatedSecondsRemaining <= 0 && zeroTimeCounter == 0) {
zeroTimeCounter++;
SaveTime();
}
}
var lang;
function qt(m,lng) {
$('#timeRemaining').css('display', 'none');
setTimeout("$('#EOMQuiz').submit();", m * 1000);
lang = lng;
setTimeout('updateQ('+ m +')', 1000);
}
function updateQ(m) {
--m;
var text;
if (lang == 'es') {
text = 'Entregar - ' + m + ' segundos restantes para completar la prueba';
}
else {
text = 'Submit - ' + m + ' seconds remaining to complete the quiz';
}
if (m > 0) {
setTimeout('updateQ('+m+')', 990);
}
else
{
$('#eomsubmitDiv').css('background-color', '#FF0000');
text ='Submitting... Please Wait.';
}
if (m <= 10 && m > 0)
{
if (m % 2 == 0)
{
$('#eomsubmitDiv').css('background-color', '#FFFF00');
}
else
{
$('#eomsubmitDiv').css('background-color', '#FFFFAA');
}
}
$('#eomsubmit').attr('value', text);
}
function UpdateElapsedTimer()
{
var s = secondsElapsed + (GetTickDiff()/1000);
UpdateTimer('TotalTimeClock', s, 'UP');
}
function GetTickDiff()
{
var d = new Date();
var tickDiff = d.getTime() - startTicks;
return tickDiff;
}
function UpdateRemainingTimer()
{
var s = secondsRemaining - (GetTickDiff()/1000);
estimatedSecondsRemaining = s;
if (s < 0) s = 0;
UpdateTimer('TimeRemainingClock', s, 'DOWN');
}
function UpdateTimer(ClockID,ElapsedSeconds,ClockDirection){
//check to see if we can run this code yet
if(document.getElementById && document.getElementById(ClockID) != null){
//declare vars
var _Seconds = 0;
var _Minutes = 0;
var _Hours = 0;
//Format Seconds
_Seconds = Math.floor(ElapsedSeconds % 60);
if(_Seconds <= 9) {
_Seconds = "0"+_Seconds;
}
//Format minutes
_Minutes = Math.floor(ElapsedSeconds/60 % 60);
if(_Minutes <= 9) {
_Minutes = "0"+_Minutes;
}
//Format hours
_Hours = Math.floor(ElapsedSeconds/3600 % 60);
if(_Hours <= 9){
_Hours = "0"+_Hours;
}
document.getElementById(ClockID).innerHTML = _Hours + ":" + _Minutes + ":" + _Seconds;
if (timerStatus != 'active')
{
setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',1000);
return;
}
if(ElapsedSeconds > 0 || ClockDirection == "UP"){
if(ClockDirection == "UP")
{
ElapsedSeconds = ElapsedSeconds + 1;
}
else
{
ElapsedSeconds = ElapsedSeconds - 1;
}
//setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',1000);
}
else{
//Timer has hit zero. Lets make sure the next buttons are visible.
$('#next_top').show();
$('#next_bot').show();
}
}
else if(!pageLoaded) //call function again in 100ms
{
//setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',100);
}
}
function DisplayNextButtons(){
$('#next_top').show();
$('#next_bot').show();
}
function hideNextButtons(){
$('#next_top').hide();
$('#next_bot').hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I happened to stumble upon the same code. If you were on the same site as me,
I have a potential fix.
Instead of editing the time remaining I setup a script that will click next when the time has expired. I was too lazy to check whether they are checking timestamps server side. Also the server logs will look more similar to a regular user.
Instructions:
Download the following extension for Chrome
https://chrome.google.com/webstore/detail/custom-javascript-for-web/poakhlngfciodnhlhhgnaaelnpjljija?hl=en
Navigate to the site
click the CJS chrome extension button
check "enable cjs for this host"
paste the following JS snippet into the JS box
var t=setInterval(try_hit_next,1000);
function try_hit_next(){
if (estimatedSecondsRemaining <= 0)
window.location = $('#next_top').parent()[0]['href'];
}
click save
1) No needs to assign "setInterval" to a variable t
2) Has somebody tried to make fully automated script for this resource, i mean "driving defensive course" cause it pushes popups with personal questions randomly and besides shows pages with a сourse-related questions (constantly the same), so hope it's gonna be very useful "tool" )
Unfortunately the timers are actually being kept server-side. You can watch a POST to CourseData.aspx and it will return with new values for SecondsRemaining and SecondsElapsed. These new values are used to set the client-side timers. You can change the client side variables all you want but when you move to the next page, another call to CourseData.aspx is done to fetch the server time. So the server's timers rule this entire process.
I believe the only reason you see any JS timers is to provide a (now hidden) simple "time remaining" clock for the user.
However I am willing to bet that there's a way to POST a new time or SecondsRemaining to the CourseData.aspx page, I just don't know what set of post data variables might be needed to do so.

JavaScript - Set function to return all items based on 1 or 2 selected tags (NO jQUERY)

I have some JavaScrip that is meant to check if there are any media tags selected or industry tags selected--this is so the portfolio items can be sorted and displayed accordingly in the browser.
What I have almost works 100%, but I can't figure out how to make it so that if only a media tag is selected or if only an industry tag is selected, the portfolio items should still be sorted accordingly. Currently, you have to select a media tag AND an industry tag, but I'd like users to be able to search using just a media tag OR just an industry tag.
Here is what I want to accomplish: If only a media tag is selected, then get all portfolio pieces that are associated with that media tag. If only an industry tag is selected, get all portfolio items that are associated with that industry tag. If a media tag AND industry tag are selected at the same time, get all portfolio items that are associated with BOTH.
Vanilla JS isn't my strong point so forgive me if this is a dumb question, but this has had me stumped for hours now.
No jQuery answers, please, as this whole page's functionality is built using JavaScript.
Here is the function:
var update = function () {
closeDrawer();
// update ui to reflect tag changes
// get our list of items to display
var itemsToDisplay = [];
var currentMediaTag = controlsContainer.querySelector('.media.selected');
var currentIndustryTag = controlsContainer.querySelector('.industry.selected');
if (currentMediaTag != "" && currentMediaTag != null) {
selectedMediaFilter = currentMediaTag.innerHTML;
}
if (currentIndustryTag != "" && currentIndustryTag != null) {
selectedIndustryFilter = currentIndustryTag.innerHTML;
}
if (selectedMediaFilter == "" && selectedIndustryFilter == "") {
itemsToDisplay = portfolioItems.filter(function (item) {
return item.preferred;
});
} else {
itemsToDisplay = portfolioItems.filter(function (item) {
var mediaTags = item.media_tags,
industryTags = item.industry_tags;
if(industryTags.indexOf(selectedIndustryFilter) < 0){
return false;
}
else if(mediaTags.indexOf(selectedMediaFilter) < 0){
return false;
}
else{
return true;
}
});
}
renderItems(itemsToDisplay);
}
Not entirely sure it's necessary but just in case, here is the complete JS file that handles the portfolio page:
(function ($) {
document.addEventListener("DOMContentLoaded", function (event) {
// for portfolio interaction
var portfolioGrid = (function () {
var gridSize = undefined,
parentContainer = document.querySelector('.portfolio-item-container');
containers = parentContainer.querySelectorAll('.view'),
drawer = parentContainer.querySelector('.drawer'),
bannerContainer = drawer.querySelector('.banner-container'),
thumbsContainer = drawer.querySelector('.thumbs-container'),
descriptionContainer = drawer.querySelector('.client-description'),
clientNameContainer = drawer.querySelector('.client-name'),
controlsContainer = document.querySelector('.portfolio-controls-container'),
selectedMediaFilter = "", selectedIndustryFilter = "";
var setGridSize = function () {
var windowSize = window.innerWidth,
previousGridSize = gridSize;
if (windowSize > 1800) {
gridSize = 5;
} else if (windowSize > 900) {
gridSize = 4;
} else if (windowSize > 600 && windowSize <= 900) {
gridSize = 3;
} else {
gridSize = 2;
}
if (previousGridSize != gridSize) {
closeDrawer();
}
};
var attachResize = function () {
window.onresize = function () {
setGridSize();
};
};
var getRowClicked = function (boxNumber) {
return Math.ceil(boxNumber / gridSize);
};
var getLeftSibling = function (row) {
var cI = row * gridSize;
return containers[cI >= containers.length ? containers.length - 1 : cI];
};
var openDrawer = function () {
drawer.className = 'drawer';
scrollToBanner();
};
var scrollToBanner = function () {
var mainContainer = document.querySelector('#main-container'),
mainBounding = mainContainer.getBoundingClientRect(),
scrollY = (drawer.offsetTop - mainBounding.bottom) - 10,
currentTop = document.body.getBoundingClientRect().top;
animate(document.body, "scrollTop", "", document.body.scrollTop, scrollY, 200, true);
};
var animate = function (elem, style, unit, from, to, time, prop) {
if (!elem) return;
var start = new Date().getTime(),
timer = setInterval(function () {
var step = Math.min(1, (new Date().getTime() - start) / time);
if (prop) {
elem[style] = (from + step * (to - from)) + unit;
} else {
elem.style[style] = (from + step * (to - from)) + unit;
}
if (step == 1) clearInterval(timer);
}, 25);
elem.style[style] = from + unit;
}
var closeDrawer = function () {
drawer.className = 'drawer hidden';
};
var cleanDrawer = function () {
bannerContainer.innerHTML = "";
clientNameContainer.innerHTML = "";
descriptionContainer.innerHTML = "";
thumbsContainer.innerHTML = "";
};
var resetThumbs = function () {
Array.prototype.forEach.call(thumbsContainer.querySelectorAll('.thumb'), function (t) {
t.className = "thumb";
});
};
var handleBannerItem = function (item) {
bannerContainer.innerHTML = "";
if (item.youtube) {
var videoContainer = document.createElement('div'),
iframe = document.createElement('iframe');
videoContainer.className = "videowrapper";
iframe.className = "youtube-video";
iframe.src = "https://youtube.com/embed/" + item.youtube;
videoContainer.appendChild(iframe);
bannerContainer.appendChild(videoContainer);
} else if (item.soundcloud) {
var iframe = document.createElement('iframe');
iframe.src = item.soundcloud;
iframe.className = "soundcloud-embed";
bannerContainer.appendChild(iframe);
} else if (item.banner) {
var bannerImage = document.createElement('img');
bannerImage.src = item.banner;
bannerContainer.appendChild(bannerImage);
}
};
var attachClick = function () {
Array.prototype.forEach.call(containers, function (n, i) {
n.querySelector('a.info').addEventListener('click', function (e) {
e.preventDefault();
});
n.addEventListener('click', function (e) {
var boxNumber = i + 1,
row = getRowClicked(boxNumber);
var containerIndex = row * gridSize;
if (containerIndex >= containers.length) {
// we're inserting drawer at the end
parentContainer.appendChild(drawer);
} else {
// we're inserting drawer in the middle somewhere
var leftSiblingNode = getLeftSibling(row);
leftSiblingNode.parentNode.insertBefore(drawer, leftSiblingNode);
}
// populate
cleanDrawer();
var mediaFilterSelected = document.querySelector('.media-tags .tag-container .selected');
var selectedFilters = "";
if (mediaFilterSelected != "" && mediaFilterSelected != null) {
selectedFilters = mediaFilterSelected.innerHTML;
}
var portfolioItemName = '';
var selectedID = this.getAttribute('data-portfolio-item-id');
var data = portfolioItems.filter(function (item) {
portfolioItemName = item.name;
return item.id === selectedID;
})[0];
clientNameContainer.innerHTML = data.name;
descriptionContainer.innerHTML = data.description;
var childItems = data.child_items;
//We will group the child items by media tag and target the unique instance from each group to get the right main banner
Array.prototype.groupBy = function (prop) {
return this.reduce(function (groups, item) {
var val = item[prop];
groups[val] = groups[val] || [];
groups[val].push(item);
return groups;
}, {});
}
var byTag = childItems.groupBy('media_tags');
if (childItems.length > 0) {
handleBannerItem(childItems[0]);
var byTagValues = Object.values(byTag);
byTagValues.forEach(function (tagValue) {
for (var t = 0; t < tagValue.length; t++) {
if (tagValue[t].media_tags == selectedFilters) {
handleBannerItem(tagValue[0]);
}
}
});
childItems.forEach(function (item, i) {
var img = document.createElement('img'),
container = document.createElement('div'),
label = document.createElement('p');
container.appendChild(img);
var mediaTags = item.media_tags;
container.className = "thumb";
label.className = "childLabelInactive thumbLbl";
thumbsContainer.appendChild(container);
if (selectedFilters.length > 0 && mediaTags.length > 0) {
for (var x = 0; x < mediaTags.length; x++) {
if (mediaTags[x] == selectedFilters) {
container.className = "thumb active";
label.className = "childLabel thumbLbl";
}
}
}
else {
container.className = i == 0 ? "thumb active" : "thumb";
}
img.src = item.thumb;
if (item.media_tags != 0 && item.media_tags != null) {
childMediaTags = item.media_tags;
childMediaTags.forEach(function (cMTag) {
varLabelTxt = document.createTextNode(cMTag);
container.appendChild(label);
label.appendChild(varLabelTxt);
});
}
img.addEventListener('click', function (e) {
scrollToBanner();
resetThumbs();
handleBannerItem(item);
container.className = "thumb active";
});
});
}
openDrawer();
});
});
};
var preloadImages = function () {
portfolioItems.forEach(function (item) {
var childItems = item.child_items;
childItems.forEach(function (child) {
(new Image()).src = child.banner;
(new Image()).src = child.thumb;
});
});
};
//////////////////////////////////// UPDATE FUNCTION /////////////////////////////////////
var update = function () {
closeDrawer();
// update ui to reflect tag changes
// get our list of items to display
var itemsToDisplay = [];
var currentMediaTag = controlsContainer.querySelector('.media.selected');
var currentIndustryTag = controlsContainer.querySelector('.industry.selected');
if (currentMediaTag != "" && currentMediaTag != null) {
selectedMediaFilter = currentMediaTag.innerHTML;
}
if (currentIndustryTag != "" && currentIndustryTag != null) {
selectedIndustryFilter = currentIndustryTag.innerHTML;
}
if (selectedMediaFilter == "" && selectedIndustryFilter == "") {
itemsToDisplay = portfolioItems.filter(function (item) {
return item.preferred;
});
} else {
itemsToDisplay = portfolioItems.filter(function (item) {
var mediaTags = item.media_tags,
industryTags = item.industry_tags;
if (industryTags.indexOf(selectedIndustryFilter) < 0) {
return false;
}
else if (mediaTags.indexOf(selectedMediaFilter) < 0) {
return false;
}
else {
return true;
}
});
}
renderItems(itemsToDisplay);
}
//////////////////////////////////// RENDERITEMS FUNCTION /////////////////////////////////////
var renderItems = function (items) {
var children = parentContainer.querySelectorAll('.view');
Array.prototype.forEach.call(children, function (child) {
// remove all event listeners then remove child
parentContainer.removeChild(child);
});
items.forEach(function (item) {
var container = document.createElement('div'),
thumb = document.createElement('img'),
mask = document.createElement('div'),
title = document.createElement('h6'),
excerpt = document.createElement('p'),
link = document.createElement('a');
container.className = "view view-tenth";
container.setAttribute('data-portfolio-item-id', item.id);
thumb.src = item.thumb;
mask.className = "mask";
title.innerHTML = item.name;
excerpt.innerHTML = item.excerpt;
link.href = "#";
link.className = "info";
link.innerHTML = "View Work";
container.appendChild(thumb);
container.appendChild(mask);
mask.appendChild(title);
mask.appendChild(excerpt);
mask.appendChild(link);
parentContainer.insertBefore(container, drawer);
});
containers = parentContainer.querySelectorAll('.view');
attachClick();
};
var filterHandler = function (linkNode, tagType) {
var prevSelection = document.querySelector("." + tagType + '.selected');
if (prevSelection != "" && prevSelection != null) {
prevSelection.className = tagType + ' tag';
}
linkNode.className = tagType + ' tag selected';
update();
};
var clearFilters = function (nodeList, filterType) {
Array.prototype.forEach.call(nodeList, function (node) {
node.className = filterType + " tag";
console.log("Clear filters function called");
});
}
var attachFilters = function () {
var mediaFilters = controlsContainer.querySelectorAll('.tag.media'),
industryFilters = controlsContainer.querySelectorAll('.tag.industry'),
filterToggle = controlsContainer.querySelectorAll('.filter-toggle');
// resets
controlsContainer.querySelector('.media-tags .reset')
.addEventListener('click',
function (e) {
e.preventDefault();
selectedMediaFilter = "";
clearFilters(controlsContainer.querySelectorAll('.media-tags a.tag'), "media");
update();
}
);
controlsContainer.querySelector('.industry-tags .reset')
.addEventListener('click',
function (e) {
e.preventDefault();
selectedIndustryFilter = "";
clearFilters(controlsContainer.querySelectorAll('.industry-tags a.tag'), "industry");
update();
}
);
Array.prototype.forEach.call(filterToggle, function (toggle) {
toggle.addEventListener('click', function (e) {
if (controlsContainer.className.indexOf('open') < 0) {
controlsContainer.className += ' open';
} else {
controlsContainer.className = controlsContainer.className.replace('open', '');
}
});
});
//Attaches a click event to each media tag "button"
Array.prototype.forEach.call(mediaFilters, function (filter) {
filter.addEventListener('click', function (e) {
e.preventDefault();
// var selectedMediaFilter = controlsContainer.querySelector('.media.selected');
//console.log("Media tag: " +this.innerHTML); *THIS WORKS*
filterHandler(this, "media");
});
});
Array.prototype.forEach.call(industryFilters, function (filter) {
filter.addEventListener('click', function (e) {
e.preventDefault();
// var selectedIndustryFilter = this.querySelector('.industry.selected');
// console.log("Industry tag: " +this.innerHTML); *THIS WORKS*
filterHandler(this, "industry");
});
});
};
return {
init: function () {
setGridSize();
attachResize();
attachClick();
preloadImages();
// portfolio page
if (controlsContainer) {
attachFilters();
}
}
};
})();
portfolioGrid.init();
});
}());
$ = jQuery.noConflict();
if(industryTags.indexOf(selectedIndustryFilter) < 0){
return false;
}
else if(mediaTags.indexOf(selectedMediaFilter) < 0){
return false;
}
That part is giving you headaches. Whenever no industry tag or media tag is selected this will exit the function.
Change to:
if(industryTags.indexOf(selectedIndustryFilter) < 0 && mediaTags.indexOf(selectedMediaFilter) < 0){
return false;
}
Now it will test if at least one tag is selected. If so then render items.
I made a change just to experiment with an idea, and this setup works:
if((selectedIndustryFilter !="" && industryTags.indexOf(selectedIndustryFilter) < 0) || (selectedMediaFilter !="" && mediaTags.indexOf(selectedMediaFilter) < 0)){
return false;
}
return true;
Not sure if it's the best solution ever but it seems to work and I'm not going to complain.

I want to make countdown then capatcha

Hi
I got countdown code
<script type="text/javascript">
window.onload = function() {
countDown('my_div1', '<form>1+1=<input name="d" type="text" /></form>', 10);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
elem.innerHTML = output;
clearInterval(timer);
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "Time left: "+timeparts[1];
}
},250);
}
</script>
I want when the countdown end appear CAPTCHA or question if this right, then continue to link
try to put the countdown function here
window.onload = function() {
countDown('my_div1', //here// , 10);
}
Assume that your countdown coding is working fine and you have a div in which captcha is stored say div id = "captchadiv",
<script type="text/javascript">
window.onload = function() {
//////////////////////////////////////////////////////
set the visibility of the captcha hidden here.
//////////////////////////////////////////////////////
countDown('my_div1', '<form>1+1=<input name="d" type="text" /></form>', 10);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
elem.innerHTML = output;
clearInterval(timer);
//////////////////////////////////////////////////////
set visibility of captchadiv to visibile.
//////////////////////////////////////////////////////
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "Time left: "+timeparts[1];
}
},250);
}
//////////////////////////////////////////////////////
add a function here to validate the captcha.
If validation succeeds, do success action.
If validation fails, set captcha visibility to hidden and again call the counttDown function.
//////////////////////////////////////////////////////
</script>
EDIT
Check this out. (Untested version)
<script type="text/javascript">
var mathenticate;
window.onload = function() {
countDown('my_div1', '<form>1+1=<input name="d" type="text" /></form>', 10);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
elem.innerHTML = output;
clearInterval(timer);
mathenticate = {
bounds: {
lower: 5,
upper: 50
},
first: 0,
second: 0,
generate: function()
{
this.first = Math.floor(Math.random() * this.bounds.lower) + 1;
this.second = Math.floor(Math.random() * this.bounds.upper) + 1;
},
show: function()
{
return this.first + ' + ' + this.second;
},
solve: function()
{
return this.first + this.second;
}
};
mathenticate.generate();
var $auth = $('<input type="text" name="auth" />');
$auth
.attr('placeholder', mathenticate.show())
.insertAfter('input[name="name"]');
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "Time left: "+timeparts[1];
}
},250);
}
$('#form').on('submit', function(e){
e.preventDefault();
if( $auth.val() != mathenticate.solve() )
{
alert('wrong answer!');
// If you want to generate a new captcha, then
mathenticate.generate();
}else {
document.location.href = 'http://www.overdir.com';
}
});
</script>

Categories

Resources