How to display Javascript variable in specific HTML div? - javascript

I'm very new to using Javascript and I want to display this variable on my homepage for my portfolio
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
var curDate = new Date();
var curYear = curDate.getUTCFullYear(),
curMonth = curDate.getUTCMonth(),
curDay = curDate.getUTCDate();
var myYear = 1996,
myMonth = 10,
myDay = 22;
var myAge = curYear % myYear;
if (curMonth < myMonth && curDay < myDay || curMonth < myMonth && curDay === myDay || curMonth == myMonth && curDay < myDay) {
myAge -= 1;
}
var myAgeDiv = document.getElementById('my-age');
myAgeDiv.textContent = myAge;
$('#my-age').text(myAge);
</script>
<title>My eportfolio!</title>
</head>
<body>
<div id="my-age"></div>
</body>
</html>
Edit: I've created a new html file (the same as above) with no other content external .js files and it still doesn't work. Does this mean the age displaying code is wrong?

You may try:
document.getElementById("your_div_id").innerHTML = myAge;

if your div have an ID do this using jQuery:
$('#DivID').text(myAge);
have a class:
$('.DivClass').text(myAge);
or using only javascrtipt:
document.getElementById('DivID').innerText = myAge;

HTML:
<div id="test"></div>
JS:
var d = document.getElementById('test');
d.innerHTML = myAge;

Let's say you've got a <div> like the following one:
<div id="my-age"></div>
Then you can use the document.getElementById() to get the div in JavaScript and edit its content:
var myAgeDiv = document.getElementById('my-age');
myAgeDiv.textContent = myAge;

If your variable is your_variable
Then you can use
document.getElementById('DivID').innerHTML = your_variable;

If you are using pure javascript, somehow get your element, for example:
var myElem = document.getElementById('my-element-id');
Then you can set it's innerHTML:
myElem.innerHTML = myAge.toString();
If you are using jQuery, things get simpler, getting your element becomes:
var myElem = $('#my-element-id');
And setting it's content:
myElem.html(myAge);
Or if you don't need to insert html and want to be safer:
myElem.text(myAge);

Related

Javascript Warp Time with Warp js

I'm working on a project where I need to manipulate time speed forward and backward. This module seems like what I need but I can't get it working:
https://github.com/mattbradley/warpjs/blob/master/README.md
Any help appreciated
<html>
<head>
</head>
<body>
<script src="jquery.min.js"></script>
<script src="warp.js"></script>
<div id="container"></div>
<span id="info"></span><br>
<span id="time"></span>
<span id="time2"></span>
<script>
setInterval(function() {
var now = new Date;
now = Date.warp.clock(true);
//now = Date.warp.speed(2); // DOESNT WORK?
var dateD = [now.getMonth() + 1,now.getDate(),now.getFullYear()];
var dateE = [now.getHours(),now.getMinutes(),now.getSeconds()];
var MDY = dateD.join("/");
var HMS = dateE.join(":");
time.innerHTML = (MDY);
time2.innerHTML = (HMS);
}, 20);
</script>
</body>
</html>
The wrap is a static method, it doesn't return any value(undefined is returned)
setInterval(function() {
Date.warp.speed(3);
var now = new Date;
var dateD = [now.getMonth() + 1, now.getDate(), now.getFullYear()];
var dateE = [now.getHours(), now.getMinutes(), now.getSeconds()];
var MDY = dateD.join("/");
var HMS = dateE.join(":");
time.innerHTML = (MDY);
time2.innerHTML = (HMS);
}, 1000);
Demo: Fiddle

Array sort build in function

I was wondering what's wrong with my program. Am i having a syntax error or am i missing something in my build in array sort?. I'm pretty sure the problem lies within the "for" loop but i cant seem to find it. Some suggestion or help would be great.
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function leaderboard()
{
var temp1;
var temp2;
var temp3;
var temp4;
var temp5;
temp1 = 10
temp2 = 20
temp3 = 30
temp4 = 40
temp5 = 50
var leader = new Array(5);
leader[0] = temp1;
leader[1] = temp2;
leader[2] = temp3;
leader[3] = temp4;
leader[4] = temp5;
leader.sort(function(a,b){return b-a});
var myContent = '';
for (var d=0;d<5;d++)
{
myContent += "score: " + leader[d] + "<BR>";
}
document.getElementById("leaderboard").innerHTML = myContent;
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> leaderboard() </SCRIPT>
</BODY>
</HTML>
You are trying to write the o/p to an element with id leaderboard which is not present in the page. Which is giving an error Uncaught TypeError: Cannot set property 'innerHTML' of null - it is not a syntax error.
So just create an element with the id leaderboard as shown below
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function leaderboard()
{
var temp1;
var temp2;
var temp3;
var temp4;
var temp5;
temp1 = 10
temp2 = 20
temp3 = 30
temp4 = 40
temp5 = 50
var leader = new Array(5);
leader[0] = temp1;
leader[1] = temp2;
leader[2] = temp3;
leader[3] = temp4;
leader[4] = temp5;
leader.sort(function(a,b){return b-a});
var myContent = '';
for (var d=0;d<5;d++)
{
myContent += "score: " + leader[d] + "<BR>";
}
document.getElementById("leaderboard").innerHTML = myContent;
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<div id="leaderboard"></div>
<SCRIPT LANGUAGE = "Javascript"> leaderboard() </SCRIPT>
</BODY>
</HTML>
Demo: Fiddle

Compare and Output 2 strings in JavaScript

I am new to JavaScript, and I'm trying to make a web page where if I have the same open and closing hours for 5 days a week, it will output them on the same line. For example, the hours for Monday - Friday are the same in my example so it would print out:
Monday - Friday: 6:00AM - 2:00PM
Saturday 8:00AM - 1:00PM
Sunday Closed (Without the hyphen)
When I run this in my browser, I get a blank page. Here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script>
var MondayOpen = "6:00AM - ";
var MondayClose = "2:00PM";
var TuesdayOpen = "6:00AM - ";
var TuesdayClose = "2:00PM";
var WednesdayOpen = "6:00AM - ";
var WednesdayClose = "2:00PM";
var ThursdayOpen = "6:00AM - ";
var ThursdayClose = "2:00PM";
var FridayOpen = "6:00AM - ";
var FridayClose = "2:00PM";
var SaturdayOpen = "8:00AM - ";
var SaturdayClose = "1:00PM";
var SundayOpen = "Closed";
var SundayClose = "";
var dateArray = new Array(MondayOpen, MondayClose, TuesdayOpen, TuesdayClose, WednesdayOpen, WednesdayClose, ThursdayOpen, ThursdayClose,FridayOpen, FridayClose, SaturdayOpen, SaturdayClose, SundayOpen, SundayClose);
function outputDate(){
for(int i = 0; i<dateArray.length; i++){
var current;
//Puts Open and Close time into 1 string
dateArray[i] + dateArray[i+1] = current;
//Compare the two strings
if(current.substring(0,15) == current.substring(0,15) +2)
}
$("#hours").html(<b> current <b/>);
}
var getHours = document.getElementById('hours').innterHTML = current;
}
</script>
<div id= "hours" style="font-size:10px; color:#fff;">
</div>
What am I missing here? Any help would be appreciated.
There are several mistakes here. Just to name a few:
You put int instead of var here:
for(var i = 0; i<dateArray.length; i++){
You put String instead of var here:
var curr;
You're assigning a variable to an expression? Did you mean to do it the other way around?
//Puts Open and Close time into 1 string
curr = dateArray[i] + dateArray[i+1];
You have a closing brace after your if statement...
//Compare the two strings
if(current.substring(0,15) == current.substring(0,15) +2)
{
You type innterHTML instead of innerHTML and try to do multiple assignments:
var getHours = current;
document.getElementById('hours').innerHTML = current;
You forget to enclose this in quotes:
$("#hours").html("<b> current <b/>");
EVEN after fixing all these syntax errors I get a blank page. Consider rewriting it from scratch.
In Javascript you don't need to declare String theString = "This is a string".
Just write var stringName = "This is my string."
You might want to take a step back and master JavaScript and HTML. There are many free resources available. Just to be brief, why not try Code Academy or W3 schools. That being said, here's enough of a fix to display your variables.
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<div id="hours"></div>
</body>
<script type="text/javascript">
var MondayOpen = "6:00AM - ";
var MondayClose = "2:00PM";
var TuesdayOpen = "6:00AM - ";
var TuesdayClose = "2:00PM";
var WednesdayOpen = "6:00AM - ";
var WednesdayClose = "2:00PM";
var ThursdayOpen = "6:00AM - ";
var ThursdayClose = "2:00PM";
var FridayOpen = "6:00AM - ";
var FridayClose = "2:00PM";
var SaturdayOpen = "8:00AM - ";
var SaturdayClose = "1:00PM";
var SundayOpen = "Closed";
var SundayClose = "";
var dateArray = new Array(MondayOpen, MondayClose, TuesdayOpen, TuesdayClose, WednesdayOpen, WednesdayClose, ThursdayOpen, ThursdayClose,FridayOpen, FridayClose, SaturdayOpen, SaturdayClose, SundayOpen, SundayClose);
function outputDate(){
var printOutResults;
for(i = 0; i<dateArray.length; i++) {
var current;
//Puts Open and Close time into 1 string
current = dateArray[i] + dateArray[i+1];
printOutResults += current;
//Compare the two
if(current.substring(0,15) == current.substring(0,15) +2){
$("#hours").html(current);
}
}
$("#hours").html(printOutResults);
}
outputDate();
</script>

How can a button visible only on given month and date in javascript?

I want a button to be visible on given date and month with javascript.
Javascript:
<script type="text/javascript">
function today()
{
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
if(month==1 && day==1)
{
document.getElementById('xx').style.visibility='visible';
}
else
{
document.getElementById('xx').style.visibility='hidden';
}
}
</script>
HTML:
<input type="image" SRC="/Patankar/PNH/images/click_anim.gif" id="xx" id="return1" onClick='today();' ALT="Submit Form" style="visibility:hidden;display:none" >
I tried this code but nothing happened. Please tell me my mistake.
You have two id tags on one element:
id="xx" id="return1"
Remove one of them. From your code example, you should remove id="return1".

jQuery plugin events fire only once

I am making a very minimalistic calendar plugin for the website with jQuery. I have not had much expirience with it, so I was following plugin tutorial. I have two <a> links that should change month, but unfortunately they do so only once and then both of them stop working. I suspect I have put events to a wrong place.
Sorry for quite messy code it is just a blueprint yet.
Here is the javascript.
(function($){
$.fn.extend({
jSimpleCalendar : function(currentDate)
{
return this.each(
function()
{
obj = $(this);
result = renderCalendar(currentDate);
obj.html(result);
// Event handlers
$('#JQSCMonthPrev').click(function ()
{
currentDate.setMonth(currentDate.getMonth() - 1);
result = renderCalendar(currentDate);
obj.html(result);
});
$('#JQSCMonthNext').click(function ()
{
currentDate.setMonth(currentDate.getMonth() + 1);
result = renderCalendar(currentDate);
obj.html(result);
});
});
function renderCalendar(date)
{
// Get the calendar
calendar = createMonthArray(date);
// Build xhtml
var result = '<table class="jQSCTable">';
result += '<thead><tr><td colspan=4>< ' + getMonthNames()[date.getMonth()] + ' ></td>';
result += '<td colspan=3>< ' + date.getFullYear() + ' <a href="#" id="JQSCYearNext" >></a></td></tr></thead><tbody>';
for(i=0;i<(calendar.length);i++)
{
result += '<tr>';
for (a=1; a<=7; a++)
{
result += '<td>';
if(calendar[i][a]!='N')
{
result += '<a id="JQSCLink' + calendar[i][a] + '">' + calendar[i][a] + '</a>';
}
result += '</td>';
}
result += '</tr>';
}
result += '</tbody></table>';
return result;
};
function createMonthArray(date)
{
// Get first day of month
date.setDate(1);
// Make callendar
var calendar = new Array();
// Fill empty shit from previous month
for(i=0;i<date.getDay()-1;i++)
calendar.push('N');
// Get number of days
var numberOfDays = getNumberOfDaysMonth(date);
//Fill the rest
for(i=1;i<numberOfDays+1;i++)
calendar.push(i);
// Get number of end days
var endDays = calendar.length % 7 - 1;
//Fill the empty stuff at the end
for(i=0;i<7-endDays;i++)
calendar.push('N');
//Slice to seven pieces
var slicedCalendar = new Array();
var week = 0;
slicedCalendar[0] = new Array();
for(i=1;i<calendar.length;i++)
{
slicedCalendar[week][i-week*7] = calendar[i-1];
if (((i%7)==0)&&(i!=0))
{
week++;
slicedCalendar[week] = new Array();
}
}
return slicedCalendar.splice(0, week);
};
function getNumberOfDaysMonth(date)
{
var minDays = 28;
var dateFound = false;
var oldMonth = date.getMonth();
var workDate = new Date(date.getYear(), date.getMonth(), 1);
while (!dateFound)
{
workDate.setDate(minDays+1);
var newMonth = workDate.getMonth();//new month date
if (newMonth != oldMonth)//if the month has changed
dateFound = true;
else
minDays++;
}
return minDays;
}
// Month names
function getMonthNames()
{
var month = Array();
month[0] = 'January';
month[1] = 'February';
month[2] = 'March';
month[3] = 'April';
month[4] = 'May';
month[5] = 'June';
month[6] = 'July';
month[7] = 'August';
month[8] = 'September';
month[9] = 'Octorber';
month[10] = 'November';
month[11] = 'December';
return month;
}
}
});
})(jQuery);
Here is html test.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jSimpleCalendar.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#calendar").jSimpleCalendar(new Date());
});
</script>
</head>
<body>
<div id="calendar">
</div>
</body>
</html>
Seems like what's happening is the HTML is being rewritten when you click the first time. When this happens, the click events are no longer bound to the hrefs since the older elements were removed from the DOM.
You could put the click events into it's own function and call the function after rebuilding the calendar or use event delegation. For this, append the click event on the #calendar div and track which element was clicked.
http://www.learningjquery.com/2008/03/working-with-events-part-1

Categories