Hide a div everyday except Thursday - javascript

Trying to hid the following div everyday except Thursday using this script. Can't get it to work. JS is still new, so what did I do wrong?
<div class="row">
<script type="text/javascript">
onload=function(){
var rightNow = new Date();
var day = rightNow.getDay();
var hour = rightNow.getHours();
var newDisplay = 'none'; // unless we see otherwise
if(day==1 || day==2 || day==3 || day==5 || day==6 | day==7 ) { // days hidden
if((hour>= 1) && (hour<= 24)) {
newDisplay = 'block';
}
}
document.getElementById('thursday').style.display = newDisplay;
}
</script>
<div class="col-md-12" id="thursday">
<h3 style="font-family:Capture it;text-align:center">Warrior Pointe Radio - Live tonight on AllradioX - 1900 Pacific / 2200 Eastern</h3>
</div>

Since you are setting display to none initially, you'll want to only check if it's Thursday to set it to block. You can take out the hour stuff as well. Here's the final code:
onload = function(){
var day = (new Date()).getDay();
var newDisplay = 'none'; // unless it's Thursday
if(day == 4) newDisplay = 'block';
document.getElementById('thursday').style.display = newDisplay;
};

Related

How to separate regex in javascript Hours format

I have some problem to define hours time, i want to separate hours time to 3 time type morning, evening, and night.
if time start from 00:00 to 10:00 the type time is morning,
if time start from 10:01 to 18:00 the type time is evening,
if time start from 18:01 to 23:59 the type time is night,
i have code jquery like this
$(document).ready(function(){
$('#submit').on('click',function(){
var hrs=$('#hours').val();
var nm=$('#scedule').val();
var patt = new RegExp("^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$");
var patts = patt.test(hrs);
//morning = 00:00 - 10:00
var morn = new RegExp("^([0-9]|0[0-9]|1[0-9]):[0-5][0-9]$");
var morning = morn.test(hrs);
//evening = 10:01 - 18:00
var even = new RegExp("^(1[0-9]|[0-9]):[0-5][0-9]$");
var evening = even.test(hrs);
//night = 18:01 - 00:00
var nig = new RegExp("^(1[0-9]|2[0-3]):[0-5][0-9]$");
var night = nig.test(hrs);
if ( patts == morning ) {
alert('This is Morning');
} else if (patts == evening){
alert('This is Evening');
} else if (patts == night){
alert('This is night');
} else {
alert('Format is wrong');
}
});
});
and this is my form HTML :
Scedule : <input type="text" id="scedule"><br>
Time : <input type="text" id="hours"><br>
<input type="submit" value="submit" id="submit"><br>
You don't need a regex here, just use Date:
$(document).ready(function(){
$('#submit').on('click',function(){
var hrs=$('#hours').val();
if(hrs.length != 5 || hrs.indexOf(':') < 0)
{
alert("Wrong Fromat")
return;
}
var date = new Date();
date.setHours(hrs.split(":")[0]);
date.setMinutes(hrs.split(":")[1]);
console.log(date)
if ( date.getHours() < 10) {
console.log('This is Morning');
} else if (date.getHours() > 18 && date.getMinutes > 0){
console.log('This is night');
} else{
console.log('This is Evening');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Time : <input type="text" id="hours"><br>
<input type="submit" value="submit" id="submit"><br>

How I can interpret the correct date in Javascript when the year is of the format yy?

I have defined an input that accepts only dates in HTML.
The user can enter the date manually or by using a Calendar which is defined in javascript.
I am using Javascript and Jquery to convert the input to a date:
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = new Date(lStartDateText);
var lEffEndDate = new Date(lEndDateText);
My problem is that when the user enters the following date manually 1/1/50 is interpreted as 1/1/1950 but 1/1/49 is interpreted as 1/1/2049. I want it always to be interpreted as 20xx.
On the other hand the Calendar allows the user to choose a year from 2006 to 2021 in case the user wants to choose a date from it and not enter it manually.
Hope I can get some help here ??
Try this
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = ReFormatDate(lStartDateText);
var lEffEndDate = ReFormatDate(lEndDateText);
function ReFormatDate(dateString) {
var dateParts = dateString.split("/");
if (dateParts[2].length === 2) {
dateParts[2] = "20" + dateParts[2];
}
return new Date(dateParts.join("/"));
}
use this
var lStartDateText = "1/1/50" ;
var lEndDateText = "1/1/49" ;
var res = lStartDateText.slice(4);
var starttext = lStartDateText.replace(res,"20"+res);
var res1 = lEndDateText.slice(4);
var endtext = lEndDateText.replace(res1,"20"+res1);
alert(starttext);
alert(endtext);
var lEffStartDate = new Date(starttext);
alert("start date"+lEffStartDate);
var lEffEndDate = new Date(endtext);
alert("End Date"+lEffEndDate);
If you know your getting the last 2 digits of the year (50), and you know you always want to add the first 2 digits, which are constant (20), that's a slight modification to your code:
var lStartDateText = '20' + $j("#DateStarte").val();
var lEndDateText = '20' + $j("#DateEnd").val();
Note that this is not particularly robust, e.g. if the user enters text which is not a date you might end up with a string like '20hi', but that may be outside the scope of your question and it will be parsed as an invalid date.
$('#year').on('change keyup', function() {
var y = $('#year').val();
if (y.length === 2) {
y = '20' + y
}
if (y.length === 4) {
var dateY = new Date();
dateY.setFullYear(y);
$('#result').html(dateY);
} else {
$('#result').html('No YY or YYYY date found');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text">
<div id="result"></div>
i hope it's will be help you.
$('#year').on('change keyup', function() {
var right_date = $('#year').val();
var data = $('#year').val().split('/');
if (data[2].length == 2){
var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(0,2));
$('#result').html(data[0]+'/'+data[1]+'/'+twoDigitsCurrentYear + data[2]);
}
else {
$('#result').html(right_date);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text" placeholder="dd/mm/yy">
<div id="result"></div>

console.log gives undefined on a variable

I have a timer function (it calculates how many words were read in given time but my code doesn't work).
It says:
"Uncaught ReferenceError: startTime is not defined"
on line:
"testTime = (stopTime - startTime)/1000 + testTime;"
HTML
<button class="btn" id="start">Start Reading</button>
<div id="page1" style="display: block;"><p class="title">
Text goes here
</div>
<button class="btn" id="stop">Finished!</button>
<span id="wordValue"></span>
<span id="timeValue"></span>
JAVASCRIPT
function runTest(){
testRunning = false;
restart = false;
var testTime = 0;
jQuery('#start').click(function(){
startTime = new Date().getTime();
testRunning = true;
});
jQuery('#stop').click(function(){
stopTime = new Date().getTime();
testTime = (stopTime - startTime)/1000 + testTime;
testRunning = false;
// set wpm = calculated words per minute
wpm = Math.round(wordCount('#page1') / (testTime / 60));
// set difference = calculated difference between words per minute and national average (250)
difference = Math.round(100*((wpm/250)-1));
if (difference < 0) {
difference = difference*-1 + '% slower';
} else {
difference = difference+'% faster';
}
});
I think startTime is not defined because it's a local variable to jQuery('#start').click. Try define startTime upper
var testRunning = false;
var restart = false;
var testTime = 0;
var startTime = 0; // here
Ran this on jsfiddle and it worked fine:
https://jsfiddle.net/d3eqmbv5/
Just had to remove:
function runTest(){
And I made a fake wordCount function for testing purposes.
There is a missing parenthesis first if you look at this jsfiddle and tape F12, so what can be the next step ? to shutt the function right after or at the end of the complete block of code ?
function runTest(){
testRunning = false;
restart = false;
var testTime = 0;
https://jsfiddle.net/qugp3fot/

Enable Button during certain day & time

I am trying to enable a button ONLY during 5PM to 10PM every day, except Monday.
When the button is disabled, <p></p> should show up (like a notification to the visitor why it is disabled.)
I did try to write the JavaScript on my own, but it seem not to work correctly. I don't know anything about that language and did the script with aid of different sites.
Here is my script:
<input class="submit" type="submit" id="checktimer" value="Check"/>
<p id=timer style="display: none;">Lorem ipsum</p>
<script type="text/javascript" defer="defer">
<!--
var enableDisable = function(){
var UTC_hours = new Date().getUTCHours() +1;
var day = new Date().getDay();
if (day == 1){
document.getElementById('checktimer').disabled = true;
document.getElementById('timer').style.display = 'block';
}
else{
if (UTC_hours > 16 && UTC_hours < 22){
document.getElementById('checktimer').disabled = false;
document.getElementById('timer').style.display = 'none';
}
else
{
document.getElementById('checktimer').disabled = true;
document.getElementById('timer').style.display = 'block';
}
}
};
setInterval(enableDisable, 1000*60);
enableDisable();
// -->
</script>
This would work:
var enableDisable = function(){
var UTC_hours = new Date().getUTCHours(); //Don't add 1 here
var day = new Date().getUTCDay(); //Use UTC here also
if (day != 1 && UTC_hours >= 17 && UTC_hours < 22){
document.getElementById('checktimer').disabled = false;
document.getElementById('timer').style.display = 'none';
}else{
document.getElementById('checktimer').disabled = true;
document.getElementById('timer').style.display = 'block';
}
};
setInterval(enableDisable, 1000*60);
enableDisable();
Cheers
DEMO
Try setting the attribute on the element, instead of a property on the element object:
document.getElementById('checktimer').setAttribute('disabled');
To remove it, use
document.getElementById('checktimer').removeAttribute('disabled');
As others have mentioned, you should cache the checktimer element in a variable, instead of looking it up each time.
A couple of other minor things I changed:
Removed those Javascript comment things you had. You don't need those.
Added quotes around the value of the id attribute for your p element.
Actually, you shouldn't enable or disable the button based on JavaScript DateTime because it gets the client machine's date, meaning that if the user changes it's system date the button will be enabled. You should verify it on the server-side code, such as PHP or ASP. There, you can check for datetime validation, and write the button on the page, or not.
Just get rid of the HTML comment <!-- or comment it with //
<script type="text/javascript">
//<!--
var enableDisable = function(){
var UTC_hours = new Date().getUTCHours() +1;
var day = new Date().getDay();
if (day == 1){
document.getElementById('checktimer').disabled = true;
document.getElementById('timer').style.display = 'block';
}
else{
if (UTC_hours > 16 && UTC_hours < 22){
document.getElementById('checktimer').disabled = false;
document.getElementById('timer').style.display = 'none';
}
else
{
document.getElementById('checktimer').disabled = true;
document.getElementById('timer').style.display = 'block';
}
}
};
setInterval(enableDisable, 1000*60);
enableDisable();
// -->
</script>
Your script should then work normally

Run function for 30 min

Here's what I want to do.
Execute a function : once, at some time of the day.
The function run for 30 minutes.
I've tried setTimeout but it doesn't fit my requirement because it run the function after X millisecond. Whereas I need the function to execute right away, at desired time for 30 minutes. Code as attached.
var d = new Date();
var hour = d.getHours();
var minute = d.getMinutes();
var day = self.getDate();
var month_name=new Array(12);
month_name[0]="January"
month_name[1]="February"
month_name[2]="March"
month_name[3]="April"
month_name[4]="May"
month_name[5]="June"
month_name[6]="July"
month_name[7]="August"
month_name[8]="September"
month_name[9]="October"
month_name[10]="November"
month_name[11]="December"
var month = month_name[self.getMonth()];
var fullDate = month+' '+day+' '+hour+':'+minute;
function someFunction() {}
function closeFunction(){
noticeDiv.css('display', 'block');
mainDiv.css('display', 'none');
}
function executeFunction(targetDate){
if (fullDate == targetDate){
setTimeout ( closeFunction(), 180000 );
}else{
someFunction();
}
}
executeFunction(targetDate);
Use setInterval Function
Syntax-> var interval = setInterval(function(){function_name()},timeout In milliseconds);
To clear Interval or stop function we use ->clearInterval(interval);
HTML
<!-- Hide by default, show at target time -->
<div id="noticeDiv" style="display: none">
<h2>Registration Closed.</h2>
</div>
<!-- Show by default, hide at target time -->
<div id="mainDiv">
<h2>Registration Open.</h2>
</div>
jQuery
$(document).ready(function () {
var d = new Date();
var hour = d.getHours();
var minute = d.getMinutes();
var day = d.getDate();
var month_name = new Array(12);
month_name[0] = "January"
month_name[1] = "February"
month_name[2] = "March"
month_name[3] = "April"
month_name[4] = "May"
month_name[5] = "June"
month_name[6] = "July"
month_name[7] = "August"
month_name[8] = "September"
month_name[9] = "October"
month_name[10] = "November"
month_name[11] = "December"
var month = month_name[d.getMonth()];
var fullDate = month + ' ' + day + ' ' + hour + ':' + minute;
console.log(fullDate);
fulldate = 'May 3 17:1';
function executeFunction(targetDate) {
x = 0;
if (fulldate == targetDate) {
//set closing time of function 180000 = 30 min.It will hide div registration open and show registration closed div.
interval = setInterval(closeFunction, 180000);
} else {
openFunction();
}
}
function openFunction() {
console.log('Registration is now open')
}
function closeFunction() {
x++;
$('#mainDiv').append(x);
if (x == 1) {
$('#noticeDiv').show();
$('#mainDiv').hide();
clearInterval(interval);
}
}
// Execute time
executeFunction('May 3 17:1');
});
Working Demo http://jsfiddle.net/cse_tushar/8r5T8/

Categories

Resources