Change div class based on date - javascript

I'm building a little webpage to list the outstanding assignments I have at college.
Here's the code:
<div class="assignment">
<div class="itemt green">DUE: 28/03/2014</div>
</div>
Here's the actual page: www.edavies.co/wkc
I would like the class green to be used if before the due date, the class amber for two weeks before the due date and finally the class red for one week before. If possible it would be cool to have black on the due date and afterwards.
Hope this makes sense. Anything is fine, PHP, JavaScript, jQuery.

check http://jsfiddle.net/NhmW7/, test it changing those dates.
the function i made for this problem.
$( ".itemt" ).each(function() {
var text=$(this).text();
var res = text.split(" ");
var resta = res[1].split("/");
var dd=resta[0];
var mm=resta[1];
var yy=resta[2]; // i couldnt test with dd/mm/yyy format, so i changed to mm/dd/yyy
var now = new Date(); //"now"
var duedate = new Date(mm+'/'+dd+'/'+yy) // due date
var diff = Math.abs(now-duedate);
var each_day = 1000 * 60 * 60 * 24;//milliseconds in a day
var days = Math.round(diff / each_day);
if(days <= 14)
$(this).removeClass("green").addClass("amber");
if(days <= 7)
$(this).removeClass("amber").addClass("red");
if(days > 14)
$(this).addClass("green");
});

As you can use PHP it would be simple.
Add a placeholder in your html
<div class="item color_by_date_id1">DUE: 28/03/2014</div>
Then you parse the page on the request, replace the placeholder with a class name based on today's date and the date intervals for the particular placeholder, which could be stored in a server side config file or better, together with the items themselves.
The actual coding I am sure you can fix, after building the site already :)

I would go with the following route:
Store your assignments in a JSON array
{
"assignments": [
{
"name": "Assignment 1",
"dueDate": "11/03/2014"
},
{
"name": "Assignment 2",
"dueDate": "11/04/2014"
},
{
"name": "Assignment 3",
"dueDate": "11/07/2014"
}
]
}
Look into Handlebars, Mustache works too
Build a template and add some custom helper functions (tutorials on Handlebars) to alter the class depending on the dueDate

You could use Javascript for this. A solution with jquery should be something like adding the code below:
<script type="text/javascript">
$(document).ready(function(){
var dueDate = new Date(2014,3, 28);
var today = new Date();
if (today>= dueDate){
// or other conditions
$(".itemt").addClass("expired");
}else{
$(".itemt").addClass("expired");
}
});
</script>
This is the idea - you can manage the css class by comparing the date in javascript. Good luck!

Related

How to Show HTML Text into Javascript

I tried to show some text into javascript but unable to do
First of all, here is the code
$('.example').each(function() {
var $t = $(this),
$w = $t.find('.widget.Text');
if ($w != undefined) {
months = $(this).text().replace($w, 'months');
days = $(this).text().replace($w, 'days');
months != false && $t.find('#example-done').text(months);
days != false ? days = Number(days) : days = 7;
}
});
// up to so...............on
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="example">
<div class="widget Text">
months=(Accept) days=(20)
</div>
</div>
Here in the above code months and days data shows I tried to implement this data in javascript
months=(Accept) its value should be Accept in Js
days=(20) its value should be 20 Accept in Js
I tried the above method but not working
is there any method available to insert the above HTML format data in my Javascript
I think .split() function will resolve this problem please provide any guide (like we have to split both data with help of js and Text Trim)
Any help is highly appreciated
I just want to show months and days values into my javascript code, Please provide any code to fix this issue. I tried hard but I am unable to fix it. Like months=(Accept) and days=(20), Now how to show that value (20 and accept) into javascript? Please leave other code which I provide above Just guide me on how to show this HTML format data into js
Use .text() to get the contents of the DIV. Then you can use a regular expression to match the contents and extract the values.
$('.example').each(function() {
var $t = $(this),
$w = $t.find('.widget.Text').text();
if ($w) {
var match = $w.match(/months=\(([^)]*)\)\s+days=\((\d+)\)/);
if (match) {
var months = match[1];
var days = Number(match[2]);
console.log(`Months = ${months}, Days = ${days}`);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="example">
<div class="widget Text">
months=(Accept) days=(20)
</div>
</div>
See Reference - What does this regex mean? for explanations of the regular expression details.
Change
months = $(this).text().replace($w, 'months');
days = $(this).text().replace($w, 'days');
months != false && $t.find('#example-done').text(months);
days != false ? days = Number(days) : days = 7;
to
let a = $t.text().match(/months=\(([^(]*)\)\s+days=\(([^(]*)\)/);
months = a[1]; days = a[2];
days = days === '' ? 7 : +days;

display an image in a web page using javascript arrays

I'm trying to automate my website by setting predetermined monthly featured videos.
I have JavaScript files already saved w/ the annual data for that particular year - e.g. choose_2017_video.js as well as 2018 & 2019 files. Each image URL text and description text I set in arrays but I can't seem to get them to display. Each array element corresponds to a month [0-11].
The getMonth() method will be the way of retrieving the data.
Somehow, I need to import the song info. into the HTML roughly like this:
<h2 align="center">Video of the month: javascript:song_info[mnth];</h2>
I also need to be able to import the corresponding image path which is saved in a parallel array (of filenames).
var song_info[12], img_URL[12], mnth = today().getMonth();
song_info[7] = "Newsboys - God's Not Dead"; // example data
img_URL[7] = "Newsboys-Gods_Not_Dead_video.JPG";
This site won't let me correctly describe how I'll display the img code using the img_URL element.
Can someone give me examples of how I can import the song information into the h2 code example and img src code?
This might be done a lot easier in an ASP script since I'm more familiar w/ BASIC. JS wasn't even conceived until after I had entered the workforce after a couple yrs. in college.
My intent is to declare new arrays and a pointer variable. The pointer is supposed to determine the month from the current date. One array holds the description of the song while the other holds the filename of the screenshot to be used to launch the YouTube URL in a different browser tab. If I wanted to embed the video, I would just use HTML5 code. It is called by a script src="JSfilename" from an HTML file.
Here is one of the JS files:
var song_info[12], img_URL[12], mnth = today().getMonth();
song_info[0] = "Sidewalk Prophets - Help Me Find It";
song_info[1] = "TobyMac with Kirk Franklin & Mandisa - Lose Your Soul";
song_info[2] = "MercyMe - Dear Younger Me";
song_info[3] = "Kari Jobe - I Am Not Alone";
song_info[4] = "Danny Gokey - Tell Your Heart to Beat Again";
song_info[5] = "Hawk Nelson - Drops In the Ocean";
song_info[6] = "Plumb - Exhale";
song_info[7] = "Newsboys - God's Not Dead";
song_info[8] = "Francesca Battistelli - Holy Spirit";
song_info[9] = "Brandon Heath - Give Me Your Eyes";
song_info[10] = "Matthew West - Strong Enough";
song_info[11] = "Jordan Feliz - The River";
img_URL[0] = "Sidewalk_Prophets-Help_Me_Find_It_video.png";
img_URL[1] = "TobyMac-LoseMySoul_video.png";
img_URL[2] = "MercyMe-DearYoungerMe_video.png";
img_URL[3] = "KariJobe-IAmNotAlone_video.png";
img_URL[4] = "DannyGokey-TellYourHeartToBeatAgain_video3.PNG";
img_URL[5] = "HawkNelson-DropsInTheOcean_video.PNG";
img_URL[6] = "Plumb-Exhale_video.PNG";
img_URL[7] = "Newsboys-Gods_Not_Dead_video.JPG";
img_URL[8] = "FrancescaBattistelli-HolySpirit_video.JPG";
img_URL[9] = "BrandonHeath-GiveMeYourEyes_video.JPG";
img_URL[10] = "Matthew_West-StrongEnough_video.JPG";
img_URL[11] = "JordanFeliz-TheRiver_video.PNG";
So to be clear, you want something like
<h2 align="center">Video of the month: {your_random_video_name_from_your_JSFile}</h2>
So why not just doing this :
<h2 align="center" id="video_name">Video of the month:</h2>
<img src="#" alt="" id="video_preview"/>
<script>
var today = new Date();
var song_info = new Array, img_URL = new Array, mnth = today.getMonth();
song_info[9] = "CHVRCHES - Leave A Trace"; // example data
img_URL[9] = "http://diymag.com/media/img/Artists/C/Chvrches/October-cover/_1500x1000_crop_center-center_75/chvrches-mike-massaro-diy-2015-05.jpg";
song_info[10] = "Newsboys - God's Not Dead"; // example data
img_URL[10] = "Newsboys-Gods_Not_Dead_video.JPG";
document.getElementById("video_name").insertAdjacentHTML('beforeend',song_info[mnth]);
var image = document.getElementById("video_preview");
image.src = img_URL[mnth];
</script>
Example JSFiddle

How do I integrate java script into html?

I would like to know how my code could be displayed on a webpage instead of displayed in alert boxes, how do I do this. I understand that id's ect are needed but I am a little confused of where to start. Any help would be good. Thankyou!
<!DOCTYPE html>
<html>
<script>
//Set of variables
var nameCheck = /^[a-zA-Z\s]+$/;
//eliminates anything not relevant
var numberCheck = /^[0-9\.]+$/;
//eliminates anything not relevant
var totHours = 0;
//adds total gaming hours on one day
var dayHours = 0;
//how many on one such day set in i from 1-7
var averHours = 0;
//stores the average by dividing by the tothours by 7
var mostPerDay = 0;
//calculates day with most gamed
var mostOnDay = 0;
//Most hours on ONE day
var moreDays = " ";
//adds an s to the end of days if more than one
var mpd = 0;
//most per day
var ah = 0;
//average hours
var th = 0;
//total hours
var name = prompt("What is your name?");
//asks users name
//Make sure user inputs a name that includes letters and or spaces
while (name == "null" || isNaN(name) == false || !name.match(nameCheck)){
alert("Invalid Name!");
name = prompt("What is your name?");
}
//Greets the user by name
alert("Hello " + name );
//Ask how many hours gamed on a day
for (var i = 1; i <= 7; i++){
dayHours = prompt("How many hours have you gamed on day " + i + "?")
//Reask the question if the user inputs an invald answer
while (dayHours == null || isNaN(dayHours) || dayHours > 24 || !dayHours.match(numberCheck) || dayHours < 0){
alert("Incorrect! No letters or symbols, and make sure your input is under 24");
dayHours = prompt("How many hours have you gamed on day " + i + "?")
}
//Adds to total hours
totHours += Number(dayHours)
//Calculates days with most hours gamed
if (mostPerDay > dayHours){
}
else if (mostPerDay < dayHours){
mostPerDay = Number(dayHours);
mostOnDay = i;
}
else if (mostPerDay = dayHours){
mostOnDay += " and " + i;
mostPerDay = Number(dayHours);
}
}
//Adds 's' to the statistics if more than one day
if (isNaN(mostOnDay) == true){
moreDays = "s ";
}
//Divides the total hours by 7 to get average over those 7 days
aver = (totHours / 7);
//Calculates and rounds to the value of 1
th = totHours.toFixed(1);
ah = aver.toFixed(2);
mpd = mostPerDay.toFixed(1);
//States calculated statistics
alert("\nTotal gaming hours this week " + th + "\nAverage gaming hours this week " + ah + "\nMost on one day" + moreDays + mostOnDay + " for " + mpd + " hours." );
//Comments on average hours per day gamed
if (averHours <= 2){
alert("Healthy amount of gaming this week")
}
else if (averHours <= 24){
alert("Unhealthy amount of gaming this week")
}
</script>
</html>
There are several ways to include JavaScript in an HTML document:
Put the JavaScript code in a separate filename.js document and refer to it in the header of the HTML document (that is, between <head> and </head>) as follows: <script type="text/javascript" src="filename.js"></script>. This is the "cleanest" option as it separates functionality (JavaScript) from structure (HTML).
Put the JavaScript code directly in the header of the HTML document; that is, between <script type="text/javascript"> and </script> (no src attribute here)
In the body of the HTML document, again between <script> and </script>, for example when you want to dynamically add text with document.write('');
Changing the text in a <div id="mydiv"> can be done by accessing it via its id:
document.getElementById('mydiv').innerText = 'text';
or through the variants innerHTML, outerText or outerHTML.
For easy DOM manipulation, you may want to look into jQuery. Also, keep in mind that the JavaScript code in the header or external file will be executed immediately, which may cause errors if certain parts of the document body aren't loaded yet. jQuery offers an elegant solution by wrapping the code in
$(document).ready(function () {
// code here
});
Good luck!
A simple method to do this would be to include a link to an external javascript file:
<script src="path/myfile.js"></script>
at the bottom of your html file. If your script requires jQuery, make sure it is linked as an external script before your script. You can reference html elements in your javascript file by giving your html tags an id or class. For example:
In HTML:
<div id = "mydiv"> </div>
Select element in JS:
$('#mydiv')
If you are trying to make your web page more reactive, you may want to look into jquery. It's a lightweight javascript library that can help you make your web page more interactive. Check out the tutorial below:
http://www.w3schools.com/jquery/
I don't entirely understand your question, but just in case you are asking if the javascript will literally show up on your web page, it won't unless you display it as text. If you want to debug your javascript code, you can use developer tools on Chrome or something like it on other browsers:
https://developer.chrome.com/devtools

reset rich:calendar value on jsf form using java script

I am trying to reset value of rich:calender input box via java script but couldnt do it any way at all. the UI of my form (snippet only) is...
<rich:calendar id="startDate" datePattern="dd MMM yyyy" value="#{classBean.startDate}" popup="true" onchanged="calcDuration();">
</rich:calendar>
the java script is
function calcDuration()
{
sdate =$('frm_course:startDate').component.getSelectedDateString("dd MMM
yyyy");
var currentdate = new Date();
var sdatecmp = new Date(sdate);
if(sdatecmp > currentdate)
{
alert('The Start Date is Greater than today!');
$('frm_viewCourseDetail:startDate').component.value = ""; // 1
document.getElementById('frm_course:startDate').value =""; // 2
}
}
None of the lines 1 and 2 resets the richcalender's value. Help is required here. thanks.
The calendar (and other components) is backed by a JavaScript object which has the methods you need.
Use either #{rich:component('startDate')} or RichFaces.$('startDate') to get a reference to that object and then call resetValue().
For other methods check the docs

Javascript/jquery age verification popup for magento

Okay, so I tried to integrate this datepicker to my magento page for the purpose of age verification.
I have successfully added the required CSS and jQuery script files to the head section of my magento page but I can't figure out where to add the html.
The package source is available here along with the html and javascript files.
I want to modify it so that when a person is over 18, they stay on the page and if not, they get redirected to google.com.
Can't get this working because I am not sure how to add the index.html file's code to my magento page. I'd really appreciate some help.
Or is there an alternate (simpler) way to put 'Age verification' WITH cookies, without using PHP script?
You can use following script for this validation may be it's help you.
<script>
function check_dob()
{
var month = document.getElementById('month').value;
var day = document.getElementById('day').value;
var year = document.getElementById('year').value;
var dbDate = year+'-'+month+'-'+day;
var today = new Date();
var birthDate = new Date(dbDate);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
if(age<=20)
{
alert("You are under "+age+" Year")
}
}
</script>
You need to put some/all of the html into your template, probably somewhere where it will be on every page. e.g. /app/design/frontend/package/_theme_/template/page/html/header.phtml

Categories