Hidding field for a particular time - javascript

I have a text field that I need only to display for a certain period of time.
I need it to appear after 5pm and stop appearing at 7am daily.
The piece of text has been saved as a variable.
How do I do this?
Thanks

You can get time using Date() object and then show and hide your text. e.g
HTML:
<div class="someClass">Your text </div>
JavaScript:
var currentDate = new Date();
var currentTime = currentDate.getHours();
if(currentTime >=17 || currentTime <=7) {
document.getElementsByClassName('someClass')[0].style.visibility = 'visible';
} else {
document.getElementsByClassName('someClass')[0].style.visibility = 'hidden';
}

Related

How to use a function to open a link in html

I'm creating a website thats going to work like an online advent calendar; I want to be able to make sure that a link wont open until the correct day. Heres what I have so far:
<area shape="rect" coords="0,0,90,150" href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" alt="1" target="_blank" onClick="return canOpen(this)">
<script>
function canOpen(isTrue) {
var isOpen = new Date("Dec "+isTrue+", 2020 00:00:00").getTime();
var currentTime = new Date().getTime();
var timeDifference = isOpen - currentTime;
if (timeDifference > 0) {
<! Go to link>
}
else {
<! Show popup "You can't open this yet!>
}
}
</script>
How could I make it so that you can go to the link if it is past the date in question, and how would I get the value of alt out of the link and into the script?
Thanks for any help.
You can use Element.getAttribute() to get attribute alt as event date for check in script.
Then check if the current date passed event date, redirect by change site's location, or do anything else you like otherwise, if the element has redirect as default behavior (like a tag), you will need return false; to prevent default behavior.
function canOpen(element) {
var isOpen = new Date("Dec "+element.getAttribute("alt")+", 2020 00:00:00").getTime();
var currentTime = new Date().getTime();
var timeDifference = isOpen - currentTime;
if (timeDifference > 0) {
window.location.href = element.getAttribute("href");
} else {
alert("Not yet!");
// return false; // for `a` tag
}
}
I created two functions, one to set the date, and one to check if the link can open. If the release date has passed, the href of the link changes from "#" to the Youtube link. The date updates every second with setInterval.
Example on JSFiddle
Also, did I just get RickRolled?
<a id="premiere-link" href="#">Youtube Link</a>
<script>
// setInterval(canOpen, 1000);
let month, day, year, time;
const link = document.getElementById('premiere-link');
setDate(); //set date immediatly on page load
setInterval(setDate, 1000); //update date every second
function setDate() {
var dateObj = new Date();
month = dateObj.getUTCMonth() + 1; //months from 1-12
day = dateObj.getUTCDate();
year = dateObj.getUTCFullYear();
time = dateObj.getTime();
}
function canOpen(month, day){
//set month and day for release
if (month >= 11 && day >= 1) {
alert('You just got RickRolled')
link.setAttribute('href', 'https://www.youtube.com/watch?v=dQw4w9WgXcQ');
} else {
link.setAttribute('href', '#');
alert('You have to wait to get RickRolled')
}
}
link.onclick = () => {canOpen(month, day)};
</script>

How to update the time every second using "setInterval()" without the time flashing in and out every second?

I'm using a dropdown list that displays different timezones onclick using moment-timezone. For example when you click the dropdown labeled "est" it will display the time in eastern time, when you click "cst" the cst time will display and so on.
Anyways the problem I'm running into is this... I use setInterval(updateTime, 1000); to show the seconds tick up every second, now by doing this when a user clicks on "est" and then another time zone in the dropdown list like "cst" both of those times will appear and disappear every second on top of each other. I want it so when you click on an li element the previous one that was on screen will have the property of display=none. So when u click est for example est time will display and then when u click on cst the est will be display=none and the cst time will display. Man that was a mouthful.
Is there a way to accomplish this and still use the setInterval of 1second?
Here is my code...
<div>
<li>
<ul>
<li id="tmz1">est</li>
<li id="tmz2">central</li>
<li>pacific</li>
</ul>
</li>
<div id="output1"></div>
<div id="output2"></div>
</div>
$(document).ready(function(){
var output1 = document.getElementById('output1');
var output2 = document.getElementById('output2');
document.getElementById('tmz1').onclick = function updateTime(){
output2.style.display = "none";
output1.style.display = "block";
var now = moment();
var humanReadable = now.tz("America/Los_Angeles").format('hh:mm:ssA');
output1.textContent = humanReadable;
setInterval(updateTime, 1000);
}
updateTime();
});
$(document).ready(function(){
var output2 = document.getElementById('output2');
var output1 = document.getElementById('output1');
document.getElementById('tmz2').onclick = function updateTimeX(){
output1.style.display = "none";
output2.style.display = "block";
var now = moment();
var humanReadable =
now.tz("America/New_York").format('hh:mm:ssA');
output2.textContent = humanReadable;
setInterval(updateTimeX, 1000);
}
updateTimeX();
});
Perhaps this will help. I believe you've overcomplicated this just a bit. I've provided comments in the code for you to review.
Note: I did not use moment.js as it is unecessary for your task.
You need:
a time from a Date object
a timezone reference that will
change upon click
an interval that will publish the time (with
the changing TZ)
Someplace to put the output
// place to put the output
const output = document.getElementById('output');
// starting timezone
var tz = 'America/New_York';
// Capture click event on the UL (not the li)
document.getElementsByTagName('UL')[0].addEventListener('click', changeTZ);
function changeTZ(e) {
// e.target is the LI that was clicked upon
tz = e.target.innerText;
// toggle highlighted selection
this.querySelectorAll('li').forEach(el=>el.classList.remove('selected'));
e.target.classList.add('selected');
}
// set the output to the time based upon the changing TZ
// Since this is an entire datetime, remove the date with split()[1] and trim it
setInterval(() => {
output.textContent = new Date(Date.now()).toLocaleString('en-US', {timeZone: `${tz}`}).split(',')[1].trim();
}, 1000);
.selected {
background-color: lightblue;
}
<div>
<ul>
<li class="selected">America/New_York</li>
<li>America/Chicago</li>
<li>America/Los_Angeles</li>
</ul>
<div id="output"></div>
</div>
Assign your setInterval to a variable and clear it when a user selects the new value form dropdown and restart the interval with new value
var interval = setInterval(updateTime, 1000);
if(oldValue !== newValue){
clearInterval(interval)
}

Using JQuery to add a link to an element if a condition is met

I am very new to HTML, CSS and JavaScript. I am trying to use jQuery to make a button active or inactive depending on the time of day. I have managed to get the image to change correctly after defining the time now (d), an open time and a close time. However I am having problems assigning a link to the buttons depending on the time of day.
This code correctly applies a class if the time is between open and close. It also correctly applies the link to the ButtonOne div, only when the ManagersChatButtonActive class is applied, in a JSFiddle. However in SharePoint, were this will be, the link is also applied even when the time condition is not met.
How can I get the link to only be applied when the 'if' condition is met?
(This is my first time on Stack Overflow, so apologies if this is not very well laid out or explained).
$(document).ready(function() {
var d = new Date();
var open = new Date();
open.setHours(9);
open.setMinutes(0);
open.setSeconds(0);
var close = new Date();
close.setHours(18);
close.setMinutes(0);
close.setSeconds(0);
if (d >= open && d < close) {
$(".ButtonOne").addClass("ManagersChatButtonActive");
$(".ButtonOne").wrap('<a href="http://www.google.com"/>');
} else {
$(".ButtonOne").addClass("ManagersChatButtonInactive");
}
});
Make sure you wrap your method in the JQuery syntax for document on ready or on load as follows:
$(function(){
var d = new Date()
var open = new Date();
open.setHours(9);
open.setMinutes(0);
open.setSeconds(0);
var close = new Date();
close.setHours(18);
close.setMinutes(0);
close.setSeconds(0);
if (d >= open && d < close) {
$(".ButtonOne").addClass("ManagersChatButtonActive");
$(".ButtonOne").wrap('<a href="http://www.google.com"/>');
} else {
$(".ButtonOne").addClass("ManagersChatButtonInactive");
}
})
https://jsfiddle.net/aaronfranco/3xwhoh10/1/
It might also make more sense to use getTime() to use a UNIX timestamp, which is a number, instead of a date string.
$(function(){
var d = new Date().getTime();
var open = new Date();
open.setHours(9);
open.setMinutes(0);
open.setSeconds(0);
open = open.getTime()
var close = new Date();
close.setHours(18);
close.setMinutes(0);
close.setSeconds(0);
close = close.getTime()
if (d >= open && d < close) {
$(".ButtonOne").addClass("ManagersChatButtonActive");
$(".ButtonOne").wrap('<a href="http://www.google.com"/>');
} else {
$(".ButtonOne").addClass("ManagersChatButtonInactive");
}
})
Don't forget to get the current time with the getHours or getTime method. You want this to compare to your condition. These values do not have to be in a time-format, it also possible to just use some static numbers.
You can just do something like this:
var time = new Date(),
hours = time.getHours();
if (hours >= 9 && hours < 18) {
$(".ButtonOne").addClass("ManagersChatButtonActive");
$(".ButtonOne").wrap('<a href="http://www.google.com"/>');
} else {
$(".ButtonOne").addClass("ManagersChatButtonInactive");
}
Working example: https://jsfiddle.net/crix/7o4uhLxe/
Hope this helps!
I checked your code in browser with jQuery, but I don't know about SharePoint, so I guess if you just enclose your code which works fine with jQuery, in .ready() so that when document is ready only then your code is run and when the ".ButtonOne" element is initialized in dom:
$(document).ready(function(){
var d = new Date();
var open = new Date();
open.setHours(9);
open.setMinutes(0);
open.setSeconds(0);
console.info(d);
console.log(open);
var close = new Date();
close.setHours(18);
close.setMinutes(0);
close.setSeconds(0);
console.log(close);
if (d >= open && d < close) {
console.info("INSIDE");
$(".ButtonOne").addClass("ManagersChatButtonActive");
$(".ButtonOne").wrap('<a href="http://www.google.com"/>');
} else {
console.info("INSIDE ELSE");
$(".ButtonOne").addClass("ManagersChatButtonInactive");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="ButtonOne" >
This is the desired ButtonOne Div
</div>

How to Block an UI page from 7pm tp 7am

I have an UI page created using html,javascript,jquery,I need to display the UI page only for a certain period of time ie,.. 7am tp 7pm. So after evening 7pm, when i login it should display some message saying the page is blocked due to data transmission.
How will I go about it.
Thanks in advance.
Another approach is to use Cron to edit the .htaccess file on the server
You can call the following function on click event that will check for the time
access is to be blocked
function checkdate()
{
var currentdate = new Date();
var startlimit = new Date();
startlimit.setHours(7);
startlimit.setMinutes(0);
startlimit.setSeconds(0);
startlimit.setMilliseconds(0);
var endlimit = startlimit
endlimit.setHours(19);
if( (currentdate < endlimit) && (currentdate > startlimit) )
{
//block access
//show message
}
return false;
}

Showing alternative image if img src is not working properly

I'm working on a web page and I have this function which is showing the pic of the day of a parent site
function LoadPage() {
var today = new Date();
var yyyy = today.getFullYear();
var mm = today.getMonth()+ 1;
var dd = today.getDate();
var url="http://myparentsite"+yyyymmdd+"/image.jpg";
document.getElementById("img").setAttribute("src",url);
}
The pic of the day is usually set in the morning so I've a problem between midnight and 7-8 am during those hours the browser will show the "?" of "image not found".
How can I set it to show the image of the day before?
I tried
var dd2 = today.getDate() -1;
var url2="http://myparentsite"+yyyymmdd2+"/image.jpg";
but I don't know how to handle it in the function and in the Html.
Simple answer is have the parent site reference a constant image location, when you have a new daily image then overwrite the image with the new one and archive the old daily image.
<img src='http://myparentsite/imageOfTheDay.jpg'/>
otherwise you can check for an error and set it to yesterday's image
document.getElementById("img").onError = function() {
var dd2 = today.getDate() -1;
var url2="http://myparentsite"+yyyymmdd2+"/image.jpg";
document.getElementById("img").setAttribute("src",url2);
}
or check the date of the request and determine what image to show
var now = new Date();
var now_utc_hour = now.getUTCHours();
url = "http://myparentsite"+yyyymmdd+"/image.jpg";
if( now_utc_hour > 7 && now_utc_hour < 8 ) "http://myparentsite"+yyyymmdd2+"/image.jpg";
document.getElementById("img").setAttribute("src",url);
Basically, you need to handle an event on the image.
document.getElementById("img").onError = function() {
// the image didn't load properly, change the src attribute
document.getElementById("img").setAttribute("src", url2);
}
document.getElementById("img").setAttribute("src",url);
Try This:
<img src="http://myparentsite/imageOfTheDay.jpg" alt="" onerror="this.src='http://myparentsite/alternateImageOfTheDay.jpg'"/>
-Arpit

Categories

Resources