I have a ads box and i want close it to by clicking x button so after it has been closed i don't want to se it until 24 hours with cache I created a localstorage but it's not working as i expected how should i edit my example
var showCase = Math.round(+new Date() / 1000);
document.getElementById("close_ads").addEventListener("click", function () {
if (typeof localStorage.showCase == 'undefined' || parseInt(localStorage.showCase) <= (showCase - 3600)) {
localStorage.showCase = showCase;
document.getElementById('reklam_box').style.display = 'none';
}
});
<div id="ads_box">
Hi..I am a ads..
<span id="close_ads">Close ads and don't show unit for 24 hours</span>
</div>
You need to use Localstorages .setItem() and .getItem check this out.
https://www.taniarascia.com/how-to-use-local-storage-with-javascript/
So something like this
// set the item
localStorage.setItem('showCase', 3600);
//get the item
var showCase = localStorage.getItem('showCase');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
<div id="ads_box">
Hi..I am a ads..
<span id="close_ads">Close ads and don't show unit for 24 hours</span>
</div>
<script>
var dontShowUntil = new Date(new Date().getTime() + 60 * 60 * 24 * 1000);
document.getElementById("close_ads").addEventListener("click", function () {
localStorage.dontShowUntil = dontShowUntil;
document.getElementById('ads_box').style.display = 'none';
});
if (new Date(localStorage.dontShowUntil) > new Date()) {
document.getElementById('ads_box').style.display = 'none';
}
</script>
</body>
</html>
useful linkes:
https://johnresig.com/blog/dom-storage/
https://developer.mozilla.org/en-US/docs/Web/API/Storage
NOTICE : when working with localStorage with array of objects you must save it like that:
Just convert the objects to JSON strings:
localStorage.setItem("savedData", JSON.stringify(objects));
var objects = JSON.parse(localStorage.getItem("savedData")));
Related
So this code selects random image whenever a person loads my website, how can I change the code so that images are selected sequentially from first to last everytime a person loads the website and then again resets to first image when the counter reaches the end?
P.s- The code works fine on hosting server, here it gives an error i don't know why.
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
var randomNum = Math.floor(Math.random() * myPix.length);
document.getElementById("myPicture").src = myPix[randomNum];
}
<!DOCTYPE html>
<html>
<head>
<title>Random Image</title>
<script src="thumb.js"></script>
</head>
<body>
<img src="images/spacer.gif" id="myPicture" alt="some image">
</body>
</html>
You can use localstorage to achieve this. When the user enters the website, you can do something like:
var pictureIndex = localstorage.getItem("pictureIndex");
But since it may be the user's first visit, it would be better to have:
var pictureIndex = localstorage.getItem("pictureIndex") || 0;
Then, you just increment the pictureIndex and perform a modulo operation (for the case when this is the last image)
pictureIndex = (pictureIndex + 1) % myPix.length;
To save this index, you can use
localStorage.setItem('pictureIndex', pictureIndex);
Next time when the user refreshes the page (or comes back), he will get the next picture in your array.
The final code should look like this:
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
var pictureIndex = window.localStorage.getItem("pictureIndex") || 0;
pictureIndex = (pictureIndex + 1) % myPix.length;
window.localStorage.setItem("pictureIndex", pictureIndex);
document.getElementById("imgid").innerHTML = pictureIndex;
document.getElementById("myPicture").src = myPix[pictureIndex];
}
<!DOCTYPE html>
<html>
<head>
<title>Random Image</title>
<script src="thumb.js"></script>
</head>
<body>
Press "Run" multiple times to cycle through the images.
Currently showing: <span id="imgid"></span>
<img src="images/spacer.gif" id="myPicture" alt="some image">
</body>
</html>
Note that the above code might not work here (but you can test it locally) due to some security restrictions from jsfiddle. A working version can be accessed >here<
function choosePic() {
var local_item = 0;
if(localStorage.getItem('pic_key')){
local_item = parseInt(intvlocalStorage.getItem('pic_key'));
}
if(local_item >= myPix.length){
local_item = 0;
}
localStorage.setItem('pic_key', local_item + 1);
document.getElementById("myPicture").src = myPix[local_item];
}
You can use LocalStorage to achieve this. When the user enters the website, you can store the key and increment it.
Use local storage to save the data you need [e.g. visited = 3(3rd time the same person visited your website)]
Your js code can be implemented like this:
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
if (localStorage.getItem('visited') == null)
{
document.getElementById("myPicture").src = myPix[0];
localStorage.setItem('visited', 1);
}
else if (localStorage.getItem('visited') >= myPix.length)
{
localStorage.setItem('visited', 0);
document.getElementById("myPicture").src = myPix[localStorage.getItem('visited')];
}
else
{
document.getElementById("myPicture").src = myPix[localStorage.getItem('visited')];
localStorage.setItem('visited', localStorage.getItem('visited') + 1);
}
}
I need help with passing around data between two aspx pages (these aspx pages are stored in SharePoint Designer). I have created some JavaScript that does some simple calculations for metrics on our site.
https://tandemhospitalpartners.sharepoint.com/SitePages/Home.aspx
The following JavaScript is in the aspx link listed above.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">
window.onload = function ()
{
}
function p1()
{
totalPts = 137;
setTotalPts(totalPts);
divId = document.getElementById('avg'); // element represents the ID 'countdown' for the div
today = new Date(); //this represents todays date in the following format
//Weekday ex. "Tue"
//Month ex. "Aug"
//Todays Date ex. "08"
//Year ex. "2017"
//Time ex. "13:44:54 GMT - 0500 (Central Daylight Time"
svOpen = new Date(2017, 06, 17); // this represents the first day we accepted patients
one_day = 1000 * 60 * 60 * 24;
//milliseconds
//minutes
//seconds
//hours
//We have been open for 23 days
daysOpen = Math.ceil((today.getTime() - svOpen.getTime()) / (one_day));
//subtracting SVNH open date from current date
avgPts = parseFloat(totalPts)/parseFloat(daysOpen);
divId.innerHTML ="Average Patients Per Day: "+ avgPts.toFixed(1);
}
function GetDays(element)
{
var el = document.getElementById(element);
today = new Date();
var cmas = new Date(today.getFullYear(), 6, 12);
if (today.getMonth() == 6 && today.getDate() > 13) {
cmas.setFullYear(cmas.getFullYear() + 1);
}
var one_day = 1000 * 60 * 60 * 24;
el.innerHTML =" Days to open the second Hospital: "+Math.ceil((cmas.getTime() - today.getTime()) / (one_day));
}
function setTotalPts(totalPts)
{
totId = document.getElementById("leOne");
totId.innerHTML = "This is my total patients: " + totalPts.toString();
}
</script>
</head>
<body onload="p1(); GetDays('count'); setTotalPts();"+"text"> <!-- this onload is passing the div ID to the function p1( element )
element represents the ID -->
<div id='count' style="color: #e51400 ;
font-weight : 500;"></div>
</body>
<body>
<div id='avg' style="color: #e51400 ;
font-weight : 500;"></div>
</body>
<body>
<div id='leOne' style="color: #e51400 ;
font-weight : 500;"></div>
</body>
</html>
<!-- to keep a running count of the days i will have to subtract svOpen from todaysDate
My goal is to pass totalPts to an HTML ID that is on a different aspx file.
This is the link to the aspx file that contains the HTML ID I want to send it too.
https://tandemhospitalpartners.sharepoint.com/ININD/SitePages/Home.aspx
This is where I am really confused. I am not sure how to achieve this result. If anyone has ideas of how this could be done using JavaScript I would greatly appreciate it!
You cannot access another page's html from client side of another page as web is a stateless environment. But from the first page you can either pass the data through querystring to the next page or you can save data to localStorage, then navigate to the next page and retrieve data from localStorage. I prefer Querystring as it looks like its just a number you want to pass.
Suppose you have a button that opens up the second page
<asp:Button runat="server" ID="btnNext" OnClientClick="location.href='https://tandemhospitalpartners.sharepoint.com/ININD/SitePages/Home.aspx?totalPointes=' + getTotalPoints()" Text="Inind Home"></Button>
Then in the destination page the totalPoints from querystring and save it to the element. e.g.
$("#SomeID").val(getvaluefromQuerystring());
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
$("#dvValue").html(getUrlParameter("totalPointes"));
});
//This function gets the querystring value from the querystring
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="dvValue"></div>
</div>
</form>
</body>
</html>
Why am I not getting a zero, but an "18", from .getHours(), when comparing two dates that are separated by only seconds?
Here is the code:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<span id="test">starting...</span>
<script>
var a = document.getElementById("test");
window.setInterval(myHourCheck, 1000);
var originalDate = new Date();
function myHourCheck() {
var current = new Date();
var original = originalDate;
var timeDelta = current.getTime() - original.getTime();
var hours = new Date(timeDelta).getHours();
a.innerHTML = hours;
}
</script>
</body>
</html>
Stepping through confirms that only seconds separate current from original.
new Date constructs a Date object with your local time zone. The hour offset is screwing you up.
You can get around this by using the UTC versions of the methods:
new Date(0).getUTCHours() === 0
Write the JavaScript to read the number of hours worked from the user. Then write the JavaScript to calculate how much money the user made if they were paid $12/hour for the first 40 hours worked, and $18/hr for all hours worked over 40. Then use the alert() function to print the total amount to the user.
what code do I have to use
var y = prompt("Enter a Value","");
Lol #OverComplicated. The answer is there just remake a better version and try your homework before being spoonfed.
var BarryScott = {
PricePerHour: 12,
HoursWorkedByBarry: 0,
PrintPayment: function() {
if ( this.HoursWorkedByBarry > 40) {
var RemainHours = this.HoursWorkedByBarry - 40;
alert(this.PricePerHour * 40 + RemainHours * 18);
} else {
alert(this.PricePerHour * this.HoursWorkedByBarry);
}
},
AskHoursFromBarry: function() {
this.HoursWorkedByBarry = prompt("Enter Hours you worked");
this.PrintPayment();
}
}
BarryScott.AskHoursFromBarry();
Create a folder and place your index.html and javascript code inside.
Run index.html .
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Im lazy to do my assignment</title>
<script src = "billhours.js"></script>
</head>
<body>
</body>
</html>
billhours.js
var getInput = prompt("Enter Number of Hours worked");
var first40hrs = billHours(40, 12);
var over40hrs = billHours(getInput - 40, 18);
var totalSalary = first40hrs + over40hrs;
alert("Total Salary is "+totalSalary);
function billHours(hours, rate){
return hours*rate;
}
//This function only works for hours 40 and above.
//It's your job to put conditional statements if hours is below 40. Keep Coding.
Hi I am new to Javascript and am trying to create a function that checks two dates. I have read it is useful to put the JS in the head part of the document, but this is not returning anything. I am also new to stackoverflow so I hope I did this correctly. :) Does anyone see the error?
<!DOCTYPE html>
<html>
<head>
var myDate = new Date(); // Your timezone!
var myEpoch = myDate.getTime()/1000;
var deadline = '1341596750.000';
document.write(myEpoch);
document.write("<br>",deadline);
if (myEpoch < deadline) {
document.write("<p>Just in time!</p>");
} else {
document.write("<p>Too late!</p>");
}
</head>
<body>
<br><br><br><br>http://www.epochconverter.com/
</body>
</html>
You have to mention it's a script using <script>. Also you shouldn't output DOM in the <head> like you are doing with document.write. Manipulate the DOM like this instead:
<head>
<script type="text/javascript">
var myDate = new Date(); // Your timezone!
var myEpoch = myDate.getTime()/1000;
var deadline = '1341596750.000';
document.write(myEpoch);
document.write("<br>",deadline);
if (myEpoch < deadline) {
document.getElementById("useme").innerHTML("Just in time!");
} else {
document.getElementById("useme").innerHTML("Too late!");
}
</script>
</head>
<body>
<p id="useme"></p>