Firing javascript event based on time of day - javascript

I'm looking for help to see if there is an easy quick way to fire a JS event based on the time of day a website opens in the browser.
Essentially what I want to do is between 5pm-5am of the users local time zone have this script fire. The script is currently wired to a button that simply flips the class of the body of the page to "night mode". I would like the two to work in harmony, automate based on time and the ability to override with the button if you want the dark or light theme.
function toggleClass(element, className) {
if (!element || !className) {
return;
}
var classString = element.className,
nameIndex = classString.indexOf(className);
if (nameIndex == -1) {
classString += ' ' + className;
} else {
classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length);
}
element.className = classString;
}
document.getElementById('day-btn').addEventListener('click', function() {
toggleClass(document.getElementById('body'), 'night');
});
https://jsfiddle.net/simpson/57xe333n/2/

var time = new Date();
element = document.getElementById('body');
className = "night";
console.log(time.getHours());
if(time.getHours() > 17 || time.getHours < 5) {
if (!element || !className) {
return;
}
var classString = element.className,
nameIndex = classString.indexOf(className);
if (nameIndex == -1) {
classString += ' ' + className;
} else {
classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length);
}
element.className = classString;
}
This uses JS's built in Date functionalities which pull from the system. It runs a getHours() function which returns an int(0-23). The if statement (time.getHours() > 17 || time.getHours < 5) will then only run the code and change the theme if it is after 5pm or before 5 am. Hope this can get you started.

Related

How can I create a reset button for this game?

I have my current code posted, I'm trying to create a reset button. A button has already been created in my HTML, and I'm grabbing it at the bottom, and adding an event listener, which isn't working for some reason, also trying to figure out the correct code to add it for my game resets when the button is clicked. However having a difficult time with the syntax.
// Array of words
const words = ['planet', 'stars', 'astroid', 'moon', 'satilite', 'orbit', 'universe', 'umbra', 'lunar', 'space', 'astronomy', 'eclipse', 'nebula', 'mars', 'meteorite']
// guesses Array
let myGuesses = []
//variables
let wordSpace = ' - '
let guess = ' '
let space; //number of spaces in word
//score
let tries = 10
let counter ;
//Get random word
let index = Math.floor(Math.random()* words.length)
//play function
function play() {
let userInput = prompt(`would you like to play spaceman? (Y/N)`, "Y")
console.log(words[index])
for(let i = 0; i < words[index].length; i++){
console.log(words[0][i])
let div = document.createElement('div')
div.classList.add('letters')
div.innerHTML=' - '//words[0][i]
document.querySelector('.word-space').append(div)
}
}
//handle click function, inactivates buttons, and changes color to grey; once clicked
let handleclick = e => {
e.target.removeEventListener('click', handleclick)
e.target.style.backgroundColor= 'grey'
console.log(e.target.innerHTML)
myGuesses.push(e.target.innerHTML)
console.log(myGuesses)
console.log(words[index].includes(e.target.innerHTML))
if(words[index].includes(e.target.innerHTML)){
document.querySelector('.word-space').innerHTML= ' '
// let correct = document.createElement('ul')
for(let i = 0; i < words[index].length; i++){
// correct.setAttribute('id','correctLetters' )
// let guess= document.createElement('li')
// guess.setAttribute('class','guess')
console.log(words[0][i])
let div = document.createElement('div')
div.classList.add('letter')
if (myGuesses.includes(words[index][i])){
div.innerHTML = words[index][i]
} else {
div.innerHTML = ' - '
}
document.querySelector('.word-space').append(div)
}
getNumOfTries()
} else {
tries --
getNumOfTries()
}
}
function ans () {
const buttons = document.querySelectorAll('.letter')
buttons.forEach(letter => letter.addEventListener('click',handleclick))
}
ans()
function getNumOfTries (){
console.log(tries)
const showTries = document.querySelector('#myTries')
showTries.innerHTML = ' You have ' + tries + ' tries'
if(tries < 1){
setTimeout(() =>{prompt(`Would you like to try again? (Y,N)`, 'Y')
showTries.innerHTML = 'You loose!'
},2000)
}
// if(tries > 0 && words[index].length === myGuesses.length) {
if(tries > 0 && Array.from(document.querySelectorAll('.letters')).every(letter => letter.innerHTML !== ' - ')) {
// showTries.innerHTML = 'You Win!'
setTimeout(() =>{alert(`You Win!`)
showTries.innerHTML = 'You Win!'
},1000)
}
}
//reset game
let tryAgain = document.querySelector('.Try-Again')
tryAgain.addEventListener('clcik', play)
prevent
div.innerHTML=' - '//words[0][i]
document.querySelector('.word-space').append(div)
play()
You've got a typo there :)
tryAgain.addEventListener('clcik', play)
some notes to the written code:
you don't need to reference the element, if you're not going to use it elsewhere, just do:
document.querySelector('.Try-Again')?.addEventListener('click', play);
i'm not sure about what the "prevent" should do here
you haven't defined a global reference to a "div" parameter that you want to use at:
div.innerHTML=' - '//words[0][i]
use semicolon ';' by the end of each executed code for better code clarity + checkout some coding standards
use code editors like Visual Studio code or other tools - they usually have some basic code formatter (learn they shortcuts, it will optimize your coding process) + other usefull features like clicking through defined param references etc.

How to force loop to wait until user press submit button?

I have simple function which checks if entered pin code is valid. But i don't know how to force for-loop to wait until i enter code again to check again it's validity.
So how it should be - i type PIN code, then click OK button and it checks whether it's correct (if it is, i can see my account menu; if it's not i have to type it again and i have 2 chances left). My code fails, because PIN when code is wrong program should wait until i type new code and press OK button again.
I tried setTimeout(), callback(), but it doesn't work. This is what i have - a function with for-loop that just runs 3 times (as it is suppose to, but not instantly) without giving a chance to correct the PIN code.
That's whole, unfinished yet, code: http://jsfiddle.net/j1yz0zuj/
Only function with for-loop, which checks validity of PIN code:
var submitKey = function(callback)
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
for (i=0; i<3; i++)
{
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (2-i);
callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
if (i=2) console.log("blokada");
}
}
else if (digitStatus == 1)
{
}
}
Your approach is wrong. You should not make the user wait!!! You need 2 more variables at the top of your programm pincount=0 and pininputallowed. Increase pincount in the submit key function by 1 and then check if pincount<3.
Here is a corrected version of your code.
http://jsfiddle.net/kvsx0kkx/16/
var pinCount=0,
pinAllowed=true;
var submitKey = function()
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
pinCount++;
if(pinCount >= 3) {
pinAllowed = false;
onScreen.innerHTML = "<br>blokada";
}
if(pinAllowed){
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (3-pinCount);
inputLength = 0;
document.getElementById("screen").innerHTML += "<br>Wpisz kod PIN: ";
//callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
}
}
else if (digitStatus == 1)
{
}
}
You need to create much more variables to control your machine. Your add/delete digit function had conditions that were badly written and only worked if the text on the screen was short enough.
var inputLength = 0;
addDigit = function(digit){
//numKeyValue = numKeyValue instanceof MouseEvent ? this.value : numKeyValue;{
if (inputLength < pinLength) {
onScreen.innerHTML += this.value;
inputLength++;
}
//if (onScreen.innerHTML == 1234) console.log("PIN został wprowadzony");
},
delDigit = function(){
if (inputLength >= 0) {
onScreen.innerHTML = onScreen.innerHTML.slice(0, -1);
inputLength--;
}
};
If you want to empty the screen at any moment you can insert onScreen.innerHTML = ''; anywhere
ps: Thanks for the exercise and nice automat you made there.

Getting Elapsed Time in JS

Fiddle
I am making a social network and when you post something, I want to show the time. I have the current code to display the time (this isn't only the time, it's also validating and posting the text):
$('#b').click(function () {
var v = $('#type').val();
var u = $('#input').val();
if (v !== "" && u !== ""){
var time = new Date();
var currentime = Date.now();
var x = currentime - time;
$("ul").prepend("<li>" + v + "<br />Posted by " + u + " " + x +" minutes ago </li>");
$('#type, #input').css('border','');
}
else if (v == "" && u == "") {
$('#type, #input').css('border','1px solid red');
}
else if (v == "") {
$('#type').css('border','1px solid red');
$('#input').css('border','');
}
else {
$('#input').css('border','1px solid red');
$('#type').css('border','');
}
});
When the time posts, it says 0 minutes ago (like I told it to), but after any amount of time, it still says 0.
fiddle
Basically you set up a setInterval which governs ho frequently you update your time attribute. I used a span with a class .time to so you could theoretically update anything with time.
I would go further and hash your posts so you can easily retrieve each posts original time.
EDIT: added a new fiddle.

How to decode this javascript?

My question is how can I decode this JavaScript and how is encoded (with which program or online tool).
Here is the JavaScript that I want to decode:
http://pastebin.com/hZvKySjj
Every obfuscated script needs some kind of eval. In here, the lines
_L = 'constr\x75\x63\x74\x6F\x72';
[][_L][_L](_Z[_h._t4](_F))();
are doing this. _L is the string "constructor", and [].constructor.constructor is the Function constructor. It will be called with the decoded script, and the resulting function will be called. We can substitute it with an alert, paste the script in the console*, and wait for the result - we don't even need to understand how the decoding works. In your case, the result is (yes, including all the comments and linebreaks):
var alarm ="0";
var content = document;
if ((content.getElementById("wrapper") != null))
{
document.getElementById('wrapper').style.display = 'block';
}
function a ()
{
if ((content.getElementById("links") != null))
{
var temp = content.getElementById("links").innerHTML;
if ((temp.indexOf('nofollow')+1) > 0) alarm = "1";
else if ((temp.indexOf('noindex')+1) > 0) alarm = "1";
}
else alarm = "1";
}
function b ()
{
if ((content.getElementById("aa") != null) && (content.getElementById("ab") != null))
{
temp = document.getElementById("aa").href;
if ("http://uc-portaller.ru/" != temp) alarm = "1";
temp = document.getElementById("ab").innerHTML;
if ("скрипты для ucoz" != temp) alarm = "1";
}
else alarm = "1";
}
function c ()
{
if ((content.getElementById("ba") != null) && (content.getElementById("bb") != null))
{
temp = content.getElementById("ba").href;
if ("http://austere.ru/" != temp) alarm = "1";
temp = content.getElementById("bb").innerHTML;
if ("доска объявлений" != temp) alarm = "1";
}
else alarm = "1";
}
function d ()
{
if ((content.getElementById("ca") != null) && (content.getElementById("cb") != null))
{
temp = content.getElementById("ca").href;
if ("http://www.for-creative.com/" != temp) alarm = "1";
temp = content.getElementById("cb").innerHTML;
if ("темы для ucoz" != temp) alarm = "1";
}
else alarm = "1";
}
a ();
if (alarm == "0") b ();
if (alarm == "0") c ();
if (alarm == "0") d ();
if (alarm == "1") prompt('Нарушены условия использования, по всем вопросам обращайтесь в ICQ:', '376880395');
$(document).ready(function(){
//When you click on a link with class of poplight and the href starts with a #
$('a.poplight[href^=#]').click(function() {
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
//Pull Query & Variables from href URL
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
//Fade in the Popup and add close button
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('');
//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
//Apply Margin to Popup
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Fade in Background
$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
$('#fade').css({'filter' : 'alpha(opacity=0)'}).fadeIn(); //Fade in the fade layer
return false;
});
//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove();
}); //fade them both out
return false;
});
});
$.fn.tabs = function () {
return this.each(function () {
var $tabwrapper = $(this);
var $panels = $tabwrapper.find('> div');
var $tabs = $tabwrapper.find('> ul a');
$tabs.click(function () {
$tabs.removeClass('selected');
$(this).addClass('selected');
$panels
.hide() // hide ALL the panels
.filter(this.hash) // filter down to 'this.hash'
.show(); // show only this one
return false;
}).filter(window.location.hash ? '[hash=' + window.location.hash + ']' : ':first').click();
});
};
$(document).ready(function () {
// console.log(window.location.hash);
$('div.tabs').tabs();
});
*) Of course you need to be sure what you're doing. There's always a small risk that it's a malicious script, and you might have not found all evals. #jfriend00's tip on executing the decoding snippets line-by-line is a safer way.
The only way I know of to understand what this code does is to find a safe environment (in case the code has malicious intent) and execute it line-by-line in a debugger and watch what it does as it deobfuscates itself to turn itself into normal javascript. The variable names will often stay obscured, but the giant string in _O will get decoded into something (probably javascript code).
Have a look at: http://www.labnol.org/software/deobfuscate-javascript/19815/
They show you how can you do something like that, it's basically a matter of using chrome debugger to "beautify" the code and make it easier to read.
Some versions of chrome don't have the command on a context menu, just look for the command "Pretty print" (has a icon like -> {})
Once done that, you can use a javascript console to evaluate small snippets of code to reverse engineer it. Eg. the expression (at the beginning of your code)
1) (s\u0065lf + ([] * 0) * 1)
2) '\x5B'
3) ((s\u0065lf + ([] * 0) * 1)[0 ^ 0] == '\x5B')
returns this string on my browser
1) "[object Window]0"
2) "["
3) true
Just find the starting point and follow from there. Obfuscated code follows the same rules as normal one, it's just all messed up.

Javascript/jQuery - Timezone Change Script with Multiple Fields

I have written a javascript for changing the "timezone" of a field on my website using a dropdown select menu.
You can see the script here: http://jsfiddle.net/dTb76/14/
However, I have reached the limits of what I know how to do - I need the script to modify several "time" fields, however, at the moment it can only work with one field.
I've been trying to figure out what changes to make for days, however I have not been having much luck. Best I can tell, I need some kind of "foreach" statement, telling it to store the original time for each field and then modify it by whatever is selected in the select, however I am not sure how to implement that in jQuery/javascript.
Would appreciate help.
You just need to use $.each JQuery function:
$('#modTime').change(function() {
var times = $('.time');
$.each(times, function(index, value) {
var curTime = $(value).text();
curTimeHH = parseInt(curTime.split(':')[0],10);
$(value).attr('originalTime', curTime);
var modifyBy = parseInt($('#modTime').val(),10);
curTimeHH = parseInt(curTime,10) + modifyBy;
if (curTimeHH === 0) {
$(value).text('24:00');
} else if (curTimeHH > 24) {
curTimeHH = curTimeHH - 24;
$(value).text('0'+curTimeHH + ':00');
} else if (curTimeHH < 0) {
curTimeHH = curTimeHH + 24;
$(value).text(curTimeHH + ':00');
} else {
$(value).text(curTimeHH + ':00');
}
});
});​
Edit:
To retrieve the 'original time' of every field, you could do something like:
var times = $('.time');
$.each(times, function(index, value) {
var originalTime = $(value).attr('originalTime');
...
});
You'll want to use jQuery's each() method to iterate through each of your .time elements. This will allow you to grab the current time for each specific element and do your calculations on a per-element basis; otherwise, $('.time').text() and things like that will always return the value of the first element selected, which is what you're seeing.
This should get you started:
$('#modTime').change(
function(){
var modifyBy = parseInt($(this).val(),10); // Here, this refers to your select element, the element whose change event handler we're now in
$('.time').each(function(){ // each() iterates through each .time element found in the DOM individually; that's what you'd like to do
var $this = $(this), // Refers to the current .time element
curTime = $this.text(),
curTimeHH = parseInt(curTime.split(':')[0],10),
curTimeHH = parseInt(curTime,10) + modifyBy;
$this.attr('originalTime',curTime);
if (curTimeHH == 0) {
$this.text('24:00');
} else if (curTimeHH > 24) {
curTimeHH = curTimeHH - 24;
$this.text('0'+curTimeHH + ':00');
} else if (curTimeHH < 0) {
curTimeHH = curTimeHH + 24;
$this.text(curTimeHH + ':00');
} else {
$this.text(curTimeHH + ':00');
}
});
});

Categories