I am trying to make a simple search function with just javascript but for some reason which I cant figure out it doesnt show me anything when I enter something into my Searchbar. Thanks in advance. Here is the Code:
var terms = new Array();
var max = 6;
for (i=1;i<=max;i++) {
terms[i] = new Array();
}
terms[1]['search'] = 'google internet search web';
terms[1]['des'] = 'Google search';
terms[1]['lnk'] = 'http://www.google.com';
terms[2]['search'] = 'gmx mail email';
terms[2]['des'] = 'GMX Mail';
terms[2]['lnk'] = 'http://www.gmx.com';
terms[3]['search'] = 'web mail email';
terms[3]['des'] = 'Web Mail';
terms[3]['lnk'] = 'http://www.web.com';
terms[4]['search'] = 'youtube video your self';
terms[4]['des'] = 'Youtube Video';
terms[4]['lnk'] = 'http://www.youtube.com';
terms[5]['search'] = 'wikipedia search knowledge';
terms[5]['des'] = 'Wikipedia';
terms[5]['lnk'] = 'http://www.wikipedia.com';
terms[6]['search'] = 'facebook social';
terms[6]['des'] = 'Facebook';
terms[6]['lnk'] = 'https://www.facebook.com';
function search() {
var input = document.getElementById('searchbar').value.toLowerCase();
var i=0;
var list="";
var pos=-1;
if(input!="") {
for(i=1; i<=max; i++) {
pos= terms[i]['search'].indexOf(input);
if(pos!=-1) {
list= list + '<a class="search_lnk" href="' + terms[i]['des'] + '</a>' + '<br>';
}
pos=-1;
}
if(list==""){
document.getElementById("listing").innerHTML = "";
document.getElementById("listing").style.display = "none";
} else {
document.getElementById("listing").innerHTML = list;
document.getElementById("listing").style.display = "block";
}
}
}
.cont_ges {
border: 1px dotted #0080FF;
border-radius:10px;
position:absolute;
width:220px;
height:46px;
left:50%;
top:50%;
margin-left:-110px;
margin-top:-23px;
}
.ubers {
font-size:18px;
color:#800080;
font-weight:bold;
font-style:italic;
text-align:center;
position:absolute;
width 100%;
height:22px;
left:0px;
top:0px;
margin-top:-25px;
}
.such_lnk {
font-size:16px;
color:#FF8000;
font-style:italic;
text-decoration: none;
}
.suche_lnk a:hover {
color:#FFFF00;
text-decoration: underline;
z-index:10;
}
#listing {
position:absolute;
left:5px;
top:35px;
width: 120%;
overflow:auto;
}
#searchbar{
position:absolute;
left:5px;
width:90%;
}
<div class="cont_ges">
<span class="ubers">Enter</span>
<input id="searchbar" type="text" value="Search.." onClick="this.value='';" onKeyup="search();">
<div id="listing"></div>
</div>
Please correct your search function:
function search() {
var input = document.getElementById('searchbar').value.toLowerCase();
var i=0;
var list="";
var pos=-1;
if(input!="") {
for(i=1; i<=max; i++) {
pos= terms[i]['search'].indexOf(input);
if(pos!=-1) {
// You have error in this line
list= list + '<a class="search_lnk" href="'+terms[i]['lnk']+'">' + terms[i]['des'] + '</a>' + '<br>';
}
pos=-1;
}
if(list==""){
document.getElementById("listing").innerHTML = "";
document.getElementById("listing").style.display = "none";
} else {
document.getElementById("listing").innerHTML = list;
document.getElementById("listing").style.display = "block";
}
}
}
Working demo.
Just correct this line, it will work as expected ( for some reason it will not run here correctly in the test console of SO, but its working fine on html page)
if(pos!=-1) {
list= list + '<a class="search_lnk" href="' + terms[i]['des']+ '">'+terms[i]['des']+ '</a>' + '<br>';
}
var terms = new Array();
var max = 6;
for (i=1;i<=max;i++) {
terms[i] = new Array();
}
terms[1]['search'] = 'google internet search web';
terms[1]['des'] = 'Google search';
terms[1]['lnk'] = 'http://www.google.com';
terms[2]['search'] = 'gmx mail email';
terms[2]['des'] = 'GMX Mail';
terms[2]['lnk'] = 'http://www.gmx.com';
terms[3]['search'] = 'web mail email';
terms[3]['des'] = 'Web Mail';
terms[3]['lnk'] = 'http://www.web.com';
terms[4]['search'] = 'youtube video your self';
terms[4]['des'] = 'Youtube Video';
terms[4]['lnk'] = 'http://www.youtube.com';
terms[5]['search'] = 'wikipedia search knowledge';
terms[5]['des'] = 'Wikipedia';
terms[5]['lnk'] = 'http://www.wikipedia.com';
terms[6]['search'] = 'facebook social';
terms[6]['des'] = 'Facebook';
terms[6]['lnk'] = 'https://www.facebook.com';
function search() {
var input = document.getElementById('searchbar').value.toLowerCase();
var i=0;
var list="";
var pos=-1;
if(input!="") {
for(i=1; i<=max; i++) {
pos= terms[i]['search'].indexOf(input);
console.log(terms[i]['search']+pos);
if(pos!=-1) {
list= list + '<a class="search_lnk" href="' + terms[i]['des']+ '">'+terms[i]['des']+ '</a>' + '<br>';
}
pos=-1;
}
console.log(list);
if(list==""){
document.getElementById("listing").innerHTML = "";
document.getElementById("listing").style.display = "none";
} else {
document.getElementById("listing").innerHTML = list;
document.getElementById("listing").style.display = "block";
}
}
}
.cont_ges {
border: 1px dotted #0080FF;
border-radius:10px;
position:absolute;
width:220px;
height:46px;
left:50%;
top:50%;
margin-left:-110px;
margin-top:-23px;
}
.ubers {
font-size:18px;
color:#800080;
font-weight:bold;
font-style:italic;
text-align:center;
position:absolute;
width 100%;
height:22px;
left:0px;
top:0px;
margin-top:-25px;
}
.such_lnk {
font-size:16px;
color:#FF8000;
font-style:italic;
text-decoration: none;
}
.suche_lnk a:hover {
color:#FFFF00;
text-decoration: underline;
z-index:10;
}
#listing {
position:absolute;
left:5px;
top:35px;
width: 120%;
overflow:auto;
}
#searchbar{
position:absolute;
left:5px;
width:90%;
}
<div class="cont_ges">
<span class="ubers">Enter</span>
<input id="searchbar" type="text" value="Search.." onClick="this.value='';" onKeyup="search();">
<div id="listing"></div>
</div>
Work with more concentrate you have missed the clossing tags at the link and the data needed to show the link
if(pos!=-1) {
list= list + '<a class="search_lnk" href="' + terms[i]['des'] + '">'+terms[i]['des']+'</a>' + '<br>'; }
pos=-1;
}
Isn't there a JS
String.search(/regex/);
(Rhetorical Question) It takes a regular expression as its argument.
Related
I have been trying to create a system that when I hover over a specific div, specific text relating to that div appears. Each div is in the same class, with info at a different div with corresponding indexes. I was wondering if there was any way that I could get the class index of each div by hovering over them in order to show hidden information about them. (by showing the hidden info divs).
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var allPeople = [];
function win (name, info){
this.name = name;
this.info = info;
}
allPeople[0] = new win ("Shelly", "Is Cool");
allPeople[1] = new win ("Brandon", "Likes to golf");
allPeople[2] = new win ("Steve", "Plays Football");
allPeople[3] = new win ("Mia", "Is a good cook");
var i = 0;
$('document').ready(function(){
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='people'> " + allPeople[i].name +" </div>");
}
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='info'> " + allPeople[i].info +" </div>");
}
});
</script>
<style>
body {
background-color: lightblue;
}
div {
background-image: url("http://themes.wdfiles.com/local--files/semi-trans/semi-transbgtransparent.png");
color: white;
padding: 2%;
margin: 2%;
border: 3px white solid;
}
.info {
display: none;
border-color: red;
}
</style>
</head>
<body>
</body>
</html>
A simple solution can be based on saving the index of each div at creation time as a data attribute like:
$("body").append("<div class='people' data-index='" + i +"'> " + allPeople[i].name +" </div>");
var allPeople = [];
function win (name, info){
this.name = name;
this.info = info;
}
allPeople[0] = new win ("Shelly", "Is Cool");
allPeople[1] = new win ("Brandon", "Likes to golf");
allPeople[2] = new win ("Steve", "Plays Football");
allPeople[3] = new win ("Mia", "Is a good cook");
var i = 0;
$('document').ready(function(){
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='people' data-index='" + i +"'> " + allPeople[i].name +" </div>");
}
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='info' data-index='" + i +"'> " + allPeople[i].info +" </div>");
}
$('.people').hover(function(e) {
$('.info').eq($(this).data('index')).show();
}, function(e) {
$('.info:visible').hide();
});
});
body {
background-color: lightblue;
}
div {
background-image: url("http://themes.wdfiles.com/local--files/semi-trans/semi-transbgtransparent.png");
color: white;
padding: 2%;
margin: 2%;
border: 3px white solid;
}
.info {
display: none;
border-color: red;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
You can use jQuery.index():
var allPeople = [];
function win (name, info){
this.name = name;
this.info = info;
}
allPeople[0] = new win ("Shelly", "Is Cool");
allPeople[1] = new win ("Brandon", "Likes to golf");
allPeople[2] = new win ("Steve", "Plays Football");
allPeople[3] = new win ("Mia", "Is a good cook");
var i = 0;
$('document').ready(function(){
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='people'> " + allPeople[i].name +" </div>");
}
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='info'> " + allPeople[i].info +" </div>");
}
$('.people').hover(function(e) {
$('.info').eq($(this).index() % 4).show();
}, function(e) {
$('.info').eq($(this).index() % 4).hide();
});
});
body {
background-color: lightblue;
}
div {
background-image: url("http://themes.wdfiles.com/local--files/semi-trans/semi-transbgtransparent.png");
color: white;
padding: 2%;
margin: 2%;
border: 3px white solid;
}
.info {
display: none;
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
A different approach can be based on filtering the array elements (Array.prototype.filter()) in order to get the index of corresponding div.
var allPeople = [];
function win (name, info){
this.name = name;
this.info = info;
}
allPeople[0] = new win ("Shelly", "Is Cool");
allPeople[1] = new win ("Brandon", "Likes to golf");
allPeople[2] = new win ("Steve", "Plays Football");
allPeople[3] = new win ("Mia", "Is a good cook");
var i = 0;
$('document').ready(function(){
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='people'> " + allPeople[i].name +" </div>");
}
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='info'> " + allPeople[i].info +" </div>");
}
$('.people').hover(function(e) {
var txt = this.textContent.trim();
var peopleInfoIDX = 0;
allPeople.forEach(function(ele, idx) {
if (ele.name == txt)
peopleInfoIDX = idx;
});
$('.info').eq(peopleInfoIDX).show();
}, function(e) {
$('.info:visible').hide();
});
});
body {
background-color: lightblue;
}
div {
background-image: url("http://themes.wdfiles.com/local--files/semi-trans/semi-transbgtransparent.png");
color: white;
padding: 2%;
margin: 2%;
border: 3px white solid;
}
.info {
display: none;
border-color: red;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
Rather than having a linear set of divs where some are people and others are info, you can nest the info with its corresponding people div so that you can target the correct info with CSS.
HTML:
<div class="people-container">
<div class="people">Shelly</div>
<div class="info">Is Cool</div>
</div>
CSS:
.people-container:hover .info {
display: block;
}
So when someone hovers over the person's name, the info can be shown.
Your easiest and non-messy solution would be to output the index onto the div using a data-index attribute.
$("body").append("<div class='people' data-index="+ i +"> " + allPeople[i].name +" </div>");
and later retrieve the data-attribute value with
console.log($(e.target).data('index'))
I'm creating a speech to text convertor using webKitSpeechRecongizer, i followed well the tutorial about this API but I'm failing to get the returned texts and I get this error ("Uncaught TypeError: Cannot read property 'length' of undefined(…)").I don't have any idea about what this error is(just a student). Any help will be appreciated.Below is the code for speech to text convertor.
Speech to text convertor
<style type="text/css">
body{
font-family: Arial;
}
#result{
height: 200px;
border: 1px solid #ccc;
padding: 10px;
box-shadow: 0 0 10px 0 #bbb;
margin-bottom: 30px;
font-size: 14px;
line-height: 25px;
}
button{
font-size: 20px;
position: absolute;
top: 240px;
left: 50%;
}
</style>
</head>
<body>
<h4 align="center">Speech to text convertor</h4>
<div id = "result"></div>
<button onclick="startConverting();"><i class = "fa fa-microphone"> </i></button>
<script type="text/javascript">
var r = document.getElementById('result');
function startConverting (){
if('webkitSpeechRecognition' in window){
var speechRecognizer = new webkitSpeechRecognition();
speechRecognizer.continuous = true;
speechRecognizer.interimResults = true;
speechRecognizer.lang = "en-GB";
speechRecognizer.start();
var finalTranscripts = '';
speechRecognizer.onresult = function (event){
var interimTranscripts = '';
for(var i = event.resultIndex; i < event.result.length; i++){
var transcript = event.results[i][0].transcript;
transcript.replace("\n", "<br>");
if (event.results[i].isFinal){
finalTranscripts += transcript;
}else{
interimTranscripts += transcript;
}
}
r.innerHTML = finalTranscripts + '<span style = "color:#999">' + interimTranscripts + '</span>';
};
speechRecognizer.onerror = function (event){
};
}else{
r.innerHTML = 'Your browser is not supported.If Google chrome,please upgrade!';
}
}
</script>
</body>
</html>
Wov, I actually never heard of it but it seems I got it working now.
var r = document.getElementById('result');
var btn = document.getElementById('btn');
btn.addEventListener('click', startConverting);
function startConverting() {
if ('webkitSpeechRecognition' in window) {
var speechRecognizer = new webkitSpeechRecognition();
speechRecognizer.continuous = true;
speechRecognizer.interimResults = true;
speechRecognizer.lang = "en-GB";
speechRecognizer.start();
speechRecognizer.onresult = function(event) {
if (event.results.length) {
r.innerHTML = event.results[0][0].transcript;
}
};
speechRecognizer.onerror = function(event) {
};
} else {
r.innerHTML = 'Your browser is not supported.If Google chrome,please upgrade!';
}
}
Here is the fiddle: https://jsfiddle.net/mehmetb/afd1jn2L/
I'm making a syntax highlighter in Javascript and HTML. It works fine at the moment but I think it's really inefficient because I have an interval with a time of 0 which runs a function that loops through all of the characters in the text area and then inserts them into a div behind the text area to provide the syntax highlighting.
I think my lexer is really bad too, but at the moment I'm more concerned with the function running like a million times a second that loops through every character in the text area each time.
Can anyone please think of a more efficient way to do this?
There doesn't seem to be any performance problems but I'm not sure if it will work on a lower-powered machine because I don't want it to crash the browser tab because I want to have several on a page so I need it to be as efficient as possible.
I understand that its annoying to be given loads of code and asked to help, but I thought for the problem to be easiest to debug you'd need the entire code.
Here you code:
<html>
<head>
<title>My Syntax Highlighter</title>
<style type="text/css">
#container {
width: 100%;
height: 100%;
position: relative;
padding: 0px;
}
#code {
width: 100%;
height: 100%;
outline:none;
position: absolute;
background-color: transparent;
border: none;
font-family: Courier;
font-size: 22px;
color: rgba(0,0,0,.2) !important;
}
#codeb {
width: 100%;
height: 100%;
position: absolute;
font-family: Courier;
font-size: 22px;
padding: 2px 2px;
color: #000;
}
.keyword {
/*font-weight: bold;*/
color: #E42D82;
}
.string {
/*font-weight: bold;*/
color: #0086b3;
}
</style>
<script type="text/javascript">
function u() {
var code = document.getElementById("code");
var codeb = document.getElementById("codeb");
var c = "";
var tok = "";
var cc = 0;
var t = "";
var takeaway = 0;
var stringStarted = false;
var string = "";
for (var i = 0; i < code.value.length; i++) {
tok += code.value[i];
c += code.value[i];
cc++;
if (tok == "print") {
t = "<span class=\"keyword\">print</span>";
takeaway += 5;
c = c.substring(0, cc - takeaway) + t + c.substring(cc + t.length);
cc += t.length;
tok = "";
} else if (tok == "var") {
t = "<span class=\"keyword\">var</span>";
takeaway += 3;
c = c.substring(0, cc-takeaway) + t + c.substring(cc + t.length);
cc += t.length;
tok = "";
} else if (tok == "\"") {
tok = "";
if (stringStarted == false) {
stringStarted = true;
string += "\"";
} else {
stringStarted = false;
string += "\"";
t = "<span class=\"string\">" + string + "</span>";
takeaway += string.length;
c = c.substring(0, cc-takeaway) + t + c.substring(cc + t.length);
cc += t.length;
tok = "";
string = "";
}
tok = "";
} else if (tok == " ") {
if (stringStarted == true) {
string += " ";
}
c+= "";
tok = "";
} else {
if (stringStarted == true) {
string += code.value[i];
tok = "";
}
}
codeb.innerHTML = c;
//console.log("test");
};
//alert(string);
if (code.value == "") {
codeb.innerHTML = "";
}
clearI(setInterval(function(){ u(); }, 0));
}
function clearI(interval) {
clearInterval(interval);
}
var interval = setInterval(function(){ u(); }, 0);
</script>
</head>
<body>
<div id="container">
<div id="codeb"></div>
<textarea id="code" autofocus></textarea>
</div>
</body>
</html>
I have a favourites feature, but want the user to be able to remove them.
This is what it looks like:
So what I want to achieve is a "Remove" link under each item which calls the remove function, and so removes that entity.
Here is my JS:
function updateFavourite(video) {
document.getElementById('favourite').onclick = function () {
if ($.grep(myfavourite, function (item) {
return item["id"] == video["id"];
}).length == 0) {
blacklist[video["id"]] = true;
myfavourite.push(video);
var html = "<li class=\"history\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchFavouriteVideo(\'{1}\');\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myfavourite").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
}
}
}
function remove(video) {
document.getElementById('remove').onclick = function () {
myfavourite.splice(video, 1);
}
}
The problem is that it does not remove the video, and don't know how to add the "Remove" text for each entity.
Here is an example
HTML
<div id="favourites"></div>
<div id="displayList"></div>
CSS
#favourites {
width:auto;
height:100px;
}
.favourite {
width:auto;
height: auto;
margin-right:10px;
background-color:cyan;
float:left;
}
.title {
width:auto;
height: auto;
background-color:red;
border:0px;
text-align:center;
}
.picture {
width:50px;
height: 50px;
background-position:center;
display:block;
margin:0 auto;
}
.remove {
width:auto;
height: auto;
text-align:center;
}
.remove:hover {
cursor:pointer;
background-color:yellow;
}
#displayList {
min-height:20px;
clear:both;
border:1px solid black;
}
Javascript
var picsArray = [
'http://upload.wikimedia.org/wikipedia/commons/1/1b/Beys_Afroyim_with_son_%28cropped%29.jpg',
'http://upload.wikimedia.org/wikipedia/commons/8/8a/Tammam_Salam.jpg',
'http://upload.wikimedia.org/wikipedia/commons/2/27/Ratusz2007.jpg',
'http://upload.wikimedia.org/wikipedia/commons/6/60/GPN-2000-001979.jpg'
],
list = picsArray.slice(),
favourites = document.getElementById('favourites'),
displayList = document.getElementById('displayList');
function emptyNode(node) {
while (node.firstChild) {
node.removeChild(node.firstChild);
}
}
function updateDisplayList() {
emptyNode(displayList);
list.map(function (entry) {
return entry.split('/').slice(-1)[0];
}).forEach(function (shortEntry) {
var p = document.createElement('p');
p.appendChild(document.createTextNode(shortEntry));
displayList.appendChild(p);
});
}
list.forEach(function (pic) {
var favourite = document.createElement('div'),
title = document.createElement('div'),
img = document.createElement('img'),
remove = document.createElement('div');
favourite.className = 'favourite';
title.className = 'title';
img.className = 'picture';
remove.className = 'remove';
title.appendChild(document.createTextNode('Favourite'));
favourite.appendChild(title);
img.src = pic;
favourite.appendChild(img);
remove.appendChild(document.createTextNode('Remove'));
remove.addEventListener('click', function (e) {
e.target.parentNode.parentNode.removeChild(e.target.parentNode);
list = list.filter(function (ele) {
return ele !== e.target.previousSibling.src;
});
updateDisplayList();
}, false);
favourite.appendChild(remove);
favourites.appendChild(favourite);
});
updateDisplayList();
On jsFiddle
I have a JavaScript calendar which is working fine in the normal HTML files.
I need to integrate it with the dynamic text box creating when the Add button is clicked. I have modified the JavaScript to show the calendar, once the text box is clicked. It is not working for the 1st created text box, if I add another text box it is working fine.
index.php
<html>
<head>
<script src="calendar.js"></script>
<script>
intTextBox = 0;
function addElement()
{
intTextBox = intTextBox + 1;
var contentID = document.getElementById('content');
var newTBDiv = document.createElement('table');
newTBDiv.setAttribute('id','strText'+intTextBox);
newTBDiv.innerHTML ='<input type="text" name="arr1" class="calendarSelectDate" onclick="testtt();" />'
contentID.appendChild(newTBDiv);
}
function testtt()
{
popUpCal.init();
}
</script>
<link href="cal.css" rel="stylesheet">
</head>
<body>
<br/>
<form action="" method="post">
<label>Data:</label>
<?php ?>
<a href="javascript:addElement();" >Add</a>
<table><tr id="content"> <td></td></tr></table>
<div id="calendarDiv"></div>
<!--<input type="text" name="arr1" class="calendarSelectDate"/>
<input type="text" name="arr2" class="calendarSelectDate"/>
<input type="text" name="arr3" class="calendarSelectDate"/>
<input type="text" name="arr4" class="calendarSelectDate"/>
<input type="text" name="arr5" class="calendarSelectDate"/>
<input type="text" name="arr6" class="calendarSelectDate"/> -->
<!--<div style="height:20;"></div>
<div style="height:20;"></div>
<div style="height:20;"></div>
<div style="height:20;"></div>
<div style="height:20;"></div>
<div style="height:20;"></div>
<table><tr><td><div id="calendarDiv"></div></td></tr></table>-->
<?php ?>
<input type="submit" name="button" value="call" />
</form>
<?php if(isset($_REQUEST['button'])) { extract($_REQUEST);
print_r($arr); }?>
</body>
</html>
calendar.js
/*!
* Clean Calendar
* Copyright 2007-2009 Marc Grabanski (m#marcgrabanski.com) http://marcgrabanski.com
* Project Page: http://marcgrabanski.com/article/clean-calendar
* Under the MIT License */
var popUpCal = {
selectedMonth: new Date().getMonth(),
// 0-11
selectedYear: new Date().getFullYear(),
// 4-digit year
selectedDay: new Date().getDate(),
calendarId: 'calendarDiv',
inputClass: 'calendarSelectDate',
init: function() {
var x = getElementsByClass(popUpCal.inputClass, document, 'input');
var y = document.getElementById(popUpCal.calendarId);
// set the calendar position based on the input position
for (var i = 0; i < x.length; i++) {
x[i].onfocus = function() {
popUpCal.selectedMonth = new Date().getMonth();
setPos(this, y);
// setPos(targetObj,moveObj)
y.style.display = 'block';
popUpCal.drawCalendar(this);
popUpCal.setupLinks(this);
}
}
},
drawCalendar: function(inputObj) {
var html = '';
html = '<a id="closeCalender"><img src="http://www.nzbmovieseeker.com/images/close.gif"></img></a>';
html += '<table cellpadding="0" cellspacing="0" id="linksTable"><tr>';
html += ' <td><a id="prevMonth"><b><< </b></a></td>';
html += '<td colspan="7" class="calendarHeader">' + getMonthName(popUpCal.selectedMonth) + ' ' + popUpCal.selectedYear + '</td>';
html += ' <td><a id="nextMonth"><b> >></b></a></td>';
html += '</tr></table>';
html += '<table id="calendar" cellpadding="0" cellspacing="0"><tr>';
html += '</tr><tr class="weekDaysTitleRow">';
var weekDays = new Array('D', 'S', 'T', 'Q', 'Q', 'S', 'S');
for (var j = 0; j < weekDays.length; j++) {
html += '<td>' + weekDays[j] + '</td>';
}
var daysInMonth = getDaysInMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
var startDay = getFirstDayofMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
var numRows = 0;
var printDate = 1;
if (startDay != 7) {
numRows = Math.ceil(((startDay + 1) + (daysInMonth)) / 7);
// calculate the number of rows to generate
}
// calculate number of days before calendar starts
if (startDay != 7) {
var noPrintDays = startDay + 1;
} else {
var noPrintDays = 0;
// if sunday print right away
}
var today = new Date().getDate();
var thisMonth = new Date().getMonth();
var thisYear = new Date().getFullYear();
// create calendar rows
for (var e = 0; e < numRows; e++) {
html += '<tr class="weekDaysRow">';
// create calendar days
for (var f = 0; f < 7; f++) {
if ((printDate == today) && (popUpCal.selectedYear == thisYear) && (popUpCal.selectedMonth == thisMonth) && (noPrintDays == 0)) {
html += '<td id="today" class="weekDaysCell">';
} else {
html += '<td class="weekDaysCell">';
}
if (noPrintDays == 0) {
if (printDate <= daysInMonth) {
html += '<a>' + printDate + '</a>';
}
printDate++;
}
html += '</td>';
if (noPrintDays > 0) noPrintDays--;
}
html += '</tr>';
}
html += '</table>';
html += '<!--[if lte IE 6.5]><iframe src="javascript:false;" id="calendar_cover"></iframe><![endif]-->';
// add calendar to element to calendar Div
var calendarDiv = document.getElementById(popUpCal.calendarId);
calendarDiv.innerHTML = html;
// close button link
document.getElementById('closeCalender').onclick = function() {
calendarDiv.style.display = 'none';
}
// setup next and previous links
document.getElementById('prevMonth').onclick = function() {
popUpCal.selectedMonth--;
if (popUpCal.selectedMonth < 0) {
popUpCal.selectedMonth = 11;
popUpCal.selectedYear--;
}
popUpCal.drawCalendar(inputObj);
popUpCal.setupLinks(inputObj);
}
document.getElementById('nextMonth').onclick = function() {
popUpCal.selectedMonth++;
if (popUpCal.selectedMonth > 11) {
popUpCal.selectedMonth = 0;
popUpCal.selectedYear++;
}
popUpCal.drawCalendar(inputObj);
popUpCal.setupLinks(inputObj);
}
},
// end drawCalendar function
setupLinks: function(inputObj) {
// set up link events on calendar table
var y = document.getElementById('calendar');
var x = y.getElementsByTagName('a');
for (var i = 0; i < x.length; i++) {
x[i].onmouseover = function() {
this.parentNode.className = 'weekDaysCellOver';
}
x[i].onmouseout = function() {
this.parentNode.className = 'weekDaysCell';
}
x[i].onclick = function() {
document.getElementById(popUpCal.calendarId).style.display = 'none';
popUpCal.selectedDay = this.innerHTML;
inputObj.value = formatDate(popUpCal.selectedDay, popUpCal.selectedMonth, popUpCal.selectedYear);
}
}
}
}
// Add calendar event that has wide browser support
if (typeof window.addEventListener != "undefined") window.addEventListener("load", popUpCal.init, false);
else if (typeof window.attachEvent != "undefined") window.attachEvent("onload", popUpCal.init);
else {
if (window.onload != null) {
var oldOnload = window.onload;
window.onload = function(e) {
oldOnload(e);
popUpCal.init();
};
}
else window.onload = popUpCal.init;
}
/* Functions Dealing with Dates */
function formatDate(Day, Month, Year) {
Month++;
// adjust javascript month
if (Month < 10) Month = '0' + Month;
// add a zero if less than 10
if (Day < 10) Day = '0' + Day;
// add a zero if less than 10
var dateString = Year + '-' + Month + '-' + Day;
return dateString;
}
function getMonthName(month) {
var monthNames = new Array('Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'july', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro');
return monthNames[month];
}
function getDayName(day) {
var dayNames = new Array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
return dayNames[day];
}
function getDaysInMonth(year, month) {
return 32 - new Date(year, month, 32).getDate();
}
function getFirstDayofMonth(year, month) {
var day;
day = new Date(year, month, 0).getDay();
return day;
}
/* Common Scripts */
function getElementsByClass(searchClass, node, tag) {
var classElements = new Array();
if (node == null) node = document;
if (tag == null) tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\s)" + searchClass + "(\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
/* Position Functions */
function setPos(targetObj, moveObj) {
var coors = findPos(targetObj);
moveObj.style.position = 'absolute';
moveObj.style.top = coors[1] + 18 + 'px';
moveObj.style.left = coors[0] + 'px';
}
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft, curtop];
}
cal.css
/* calendar style */
#calendarDiv table, #calendarDiv th, #calendarDiv td, #calendarDiv, #calendarDiv a {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-weight: inherit;
font-style: inherit;
font-size: 12px;
font-family: inherit;
vertical-align: baseline;
}
div#calendarDiv {
display: block;
display: none;
position: relative;
border: 1px solid #777;
}
div#calendarDiv a {
cursor: pointer;
cursor: hand;
color: #000;
text-decoration: none;
}
table#calendar {
background: #ddd;
clear: both;
text-align: center;
font-size: 105%;
}
table#calendar, #linksTable {
width: 180px;
}
.calendarHeader {
background-color: #0080CC;
border-bottom: 1px solid #444;
color: #fff;
}
table#calendar tr.weekDaysTitleRow td {
background: #777;
color: #fff;
}
table#calendar tr.weekDaysRow {
background: #eee;
color: #666;
}
table#calendar td.weekDaysCell {
color: #000;
border: 1px solid #ddd;
}
table#calendar td.weekDaysCellOver {
background: #fff;
border: 1px solid #777;
}
a#closeCalender {
position: absolute;
right: 0;
bottom: 100%;
margin-bottom: 1px;
display: block;
padding: 2px;
cursor: pointer;
cursor: hand;
font-size: 60%;
letter-spacing: 1px;
}
a#closeCalender:hover {
background-color: transparent;
color: #fff;
}
div#calendarDiv table#linksTable td {
background: #000;
}
table#linksTable a {
text-align: center;
display: block;
color: #fff;
letter-spacing: 1px;
font-weight: bold;
font-size: 80%;
padding: 2px 5px;
}
table#linksTable a:hover {
background: #ddd;
color: #333;
}
a#prevMonth {
float: left;
}
a#nextMonth {
float: right;
}
td#today {
background: #999;
}
#calendar_cover {
display: none; /*sorry for IE5*/
display/**/: block; /*sorry for IE5*/
position: absolute; /*must have*/
z-index: -1; /*must have*/
filter: mask(); /*must have*/
top: -4px; /*must have*/
left: -4px; /*must have*/
width: 193px; /*must have to match width and borders*/
height: 200px; /*must have to match maximum height*/
}