Calling functions correctly in premade javascript - javascript

I got this HTML code:
<head>
<link href="default.css" title="default" rel="stylesheet" type="text/css" />
<link href="theme1.css" title="theme1" rel="stylesheet" type="text/css" />
<link href="theme2.css" title="theme2" rel="stylesheet" type="text/css" />
<link href="theme3.css" title="theme3" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<ul id="dropdown">
<li> Choose theme
<ul>
<li id="stylesheet1" > Default </li>
<li id="stylesheet2" > Theme 1 </li>
<li id="stylesheet3" > Theme 2 </li>
<li id="stylesheet4" > Theme 3 </li>
</ul>
</li>
</ul>
</body>
And I got this is the code in the separate file javascript.js:
function setActiveStyleSheet(title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
}
function getActiveStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
}
return null;
}
function getPreferredStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("rel").indexOf("alt") == -1
&& a.getAttribute("title")
) return a.getAttribute("title");
}
return null;
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
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,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
window.onload = function(e) {
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
}
window.onunload = function(e) {
var title = getActiveStyleSheet();
createCookie("style", title, 365);
}
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
// Last part
function initate()
{
var style1 = document.getElementById("stylesheet1");
var style2 = document.getElementById("stylesheet2");
var style3 = document.getElementById("stylesheet3");
var style4 = document.getElementById("stylesheet4");
style1.onclick = function () {
setActiveStyleSheet("default");
return false;
};
style2.onclick = function () {
setActiveStyleSheet("theme1");
return false;
};
style3.onclick = function () {
setActiveStyleSheet("theme2");
return false
};
style4.onclick = function () {
setActiveStyleSheet("theme3");
return false
};
}
window.onload = initate;
I'm new to javascripts and I haven't written this script myself (http://www.alistapart.com/articles/alternate/) and I managed to create the last part (as shown by comment in code) by myself to have the eventhandlers separate in the javascript file as I want and this part enables the style sheets to be changed the way I want it. But I can't figure out how to get the cookies to work as well to get the themes I'm using to be saved.
EDIT:
Since I'm new I still have a hard time figuring this code out but I've tried changing the last function initiate and used onClick eventhandlers for the saving of cookies but I can't get it to work.
I've used this:
style1.onclick = function () {
createcookie(T1, style, 7);
}
And
document.getElementById("stylesheet1").onclick(createCookie(T1, style, 7));
And when I did the changing of style sheets didn't work anymore.

This works:
style1.onclick = function () {
createcookie(T1, style, 7);
}
because what you do is you set the onclick handler to a function. You don't call the function there, you just give it away so that someone else (the browser) can call it.
This doesn't work:
document.getElementById("stylesheet1").onclick(createCookie(T1, style, 7));
because you call the function right there. What you do is:
Invoke createCookie with 3 parameters
Invoke onclick with the return value from createCookie
What you want is probably something like:
document.getElementById("stylesheet1").onclick = function() {
createCookie(T1, style, 7);
};
what this does, is create an anonymous function and sets this function to the onclick property of the element. This anonymous function, when called, will call the createCookie function.
The reason you need to do this, is because you have parameters to createCookie, and those parameters must be bound somewhere until it's time to call the function.

Related

Show a div if a cookie exists

So... I've been trying to show an element for recurrent visitors to my site.
This is how I'm trying to do it: (you can see this JSfiddle as well)
$(document).ready(function() {
// If the 'show cookie is set we show the message
if (!readCookie('show')) {
$('#hide').show();
}
else {
$("#hide").hide();
createCookie("show", true, 1);
}
return false;
});
And I'm also using this cookie functions that I took from w3schools
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
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,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
However, it's not working and I'm pretty sure it has something to do with my JQuery attempt, just not sure where my mistake is.
Thanks for any help!
---Edit Update---
Following some advices, this is what I've got now:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js"></script>
<script>
$(function(){
if(Cookies.get('previsitor')) {
$('#atc').show(1000);
}
});
</script>
</head>
<body>
<div id="atc" style="display: none">
Something I want to hide
</div>
<script>
Cookies.set ("previsitor","true",{ expires: 1 });
alert(document.cookie);
</script>
</body>
</html>
I'm using this library for my cookie management: https://github.com/js-cookie/js-cookie
However, it's still not doing what I want, I'm usin the alert(document.cookie); and looks like the cookie is not being created at all... but why!? :(
Try this. This should do the trick.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<script type="text/javascript">
//pass cookie name
if(checkCookie('the_cookies')){
$('#atc').show();
}
else{
$('#atc').hide();
}
function checkCookie($name)
{
if (typeof $.cookie($name) === 'undefined'){
// set cookie if not exists
$.cookie($name, 'the_value');
return false;
} else {
return true;
}
}
</script>
You just need to create your cookie after the if/else block
$(document).ready(function() {
// If the 'show cookie is set we show the message
if (!readCookie('show')) {
$('#hide').show();
}
else {
$("#hide").hide();
}
createCookie("show", true, 1);
});
Previously, the createCookie function wasn't being called at all since it was nested in the false condition.
Change calling
if (readCookie('show')) {
$('#hide').show();
}
else {
$("#hide").hide();
createCookie("show", true, 1);
}
return false;
});
Change this function
function readCookie(name) {
var nameEQ = name + "=";
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,c.length);
if (c.indexOf(nameEQ) == 0)
{alert(nameEQ.length,c.length);
return c.substring(nameEQ.length,c.length);}
}
return false;
}
This should work!

sortable.js don't work with other script condition.js and <body onload="contition()">

hi i run 2 scripts the first is
sorttable.js
/*
SortTable
version 2
7th April 2007
Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
Instructions:
Download this file
Add <script src="sorttable.js"></script> to your HTML
Add class="sortable" to any table you'd like to make sortable
Click on the headers to sort
Thanks to many, many people for contributions and suggestions.
Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
This basically means: do what you want with it.
*/
var stIsIE = /*#cc_on!#*/false;
sorttable = {
init: function() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
if (!document.createElement || !document.getElementsByTagName) return;
sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
forEach(document.getElementsByTagName('table'), function(table) {
if (table.className.search(/\bsortable\b/) != -1) {
sorttable.makeSortable(table);
}
});
},
makeSortable: function(table) {
if (table.getElementsByTagName('thead').length == 0) {
// table doesn't have a tHead. Since it should have, create one and
// put the first table row in it.
the = document.createElement('thead');
the.appendChild(table.rows[0]);
table.insertBefore(the,table.firstChild);
}
// Safari doesn't support table.tHead, sigh
if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
if (table.tHead.rows.length != 1) return; // can't cope with two header rows
// Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
// "total" rows, for example). This is B&R, since what you're supposed
// to do is put them in a tfoot. So, if there are sortbottom rows,
// for backwards compatibility, move them to tfoot (creating it if needed).
sortbottomrows = [];
for (var i=0; i<table.rows.length; i++) {
if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
sortbottomrows[sortbottomrows.length] = table.rows[i];
}
}
if (sortbottomrows) {
if (table.tFoot == null) {
// table doesn't have a tfoot. Create one.
tfo = document.createElement('tfoot');
table.appendChild(tfo);
}
for (var i=0; i<sortbottomrows.length; i++) {
tfo.appendChild(sortbottomrows[i]);
}
delete sortbottomrows;
}
// work through each column and calculate its type
headrow = table.tHead.rows[0].cells;
for (var i=0; i<headrow.length; i++) {
// manually override the type with a sorttable_type attribute
if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
if (mtch) { override = mtch[1]; }
if (mtch && typeof sorttable["sort_"+override] == 'function') {
headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
} else {
headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
}
// make it clickable to sort
headrow[i].sorttable_columnindex = i;
headrow[i].sorttable_tbody = table.tBodies[0];
dean_addEvent(headrow[i],"click", function(e) {
if (this.className.search(/\bsorttable_sorted\b/) != -1) {
// if we're already sorted by this column, just
// reverse the table, which is quicker
sorttable.reverse(this.sorttable_tbody);
this.className = this.className.replace('sorttable_sorted',
'sorttable_sorted_reverse');
this.removeChild(document.getElementById('sorttable_sortfwdind'));
sortrevind = document.createElement('span');
sortrevind.id = "sorttable_sortrevind";
sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : ' ▴';
this.appendChild(sortrevind);
return;
}
if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
// if we're already sorted by this column in reverse, just
// re-reverse the table, which is quicker
sorttable.reverse(this.sorttable_tbody);
this.className = this.className.replace('sorttable_sorted_reverse',
'sorttable_sorted');
this.removeChild(document.getElementById('sorttable_sortrevind'));
sortfwdind = document.createElement('span');
sortfwdind.id = "sorttable_sortfwdind";
sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : ' ▾';
this.appendChild(sortfwdind);
return;
}
// remove sorttable_sorted classes
theadrow = this.parentNode;
forEach(theadrow.childNodes, function(cell) {
if (cell.nodeType == 1) { // an element
cell.className = cell.className.replace('sorttable_sorted_reverse','');
cell.className = cell.className.replace('sorttable_sorted','');
}
});
sortfwdind = document.getElementById('sorttable_sortfwdind');
if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
sortrevind = document.getElementById('sorttable_sortrevind');
if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
this.className += ' sorttable_sorted';
sortfwdind = document.createElement('span');
sortfwdind.id = "sorttable_sortfwdind";
sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : ' ▾';
this.appendChild(sortfwdind);
// build an array to sort. This is a Schwartzian transform thing,
// i.e., we "decorate" each row with the actual sort key,
// sort based on the sort keys, and then put the rows back in order
// which is a lot faster because you only do getInnerText once per row
row_array = [];
col = this.sorttable_columnindex;
rows = this.sorttable_tbody.rows;
for (var j=0; j<rows.length; j++) {
row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
}
/* If you want a stable sort, uncomment the following line */
sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
//row_array.sort(this.sorttable_sortfunction);
tb = this.sorttable_tbody;
for (var j=0; j<row_array.length; j++) {
tb.appendChild(row_array[j][1]);
}
delete row_array;
});
}
}
},
guessType: function(table, column) {
// guess the type of a column based on its first non-blank row
sortfn = sorttable.sort_alpha;
for (var i=0; i<table.tBodies[0].rows.length; i++) {
text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
if (text != '') {
if (text.match(/^-?[£$€]?[\d,.]+%?$/)) {
return sorttable.sort_numeric;
}
// check for a date: dd/mm/yyyy or dd/mm/yy
// can have / or . or - as separator
// can be mm/dd as well
possdate = text.match(sorttable.DATE_RE)
if (possdate) {
// looks like a date
first = parseInt(possdate[1]);
second = parseInt(possdate[2]);
if (first > 12) {
// definitely dd/mm
return sorttable.sort_ddmm;
} else if (second > 12) {
return sorttable.sort_mmdd;
} else {
// looks like a date, but we can't tell which, so assume
// that it's dd/mm (English imperialism!) and keep looking
sortfn = sorttable.sort_ddmm;
}
}
}
}
return sortfn;
},
getInnerText: function(node) {
// gets the text we want to use for sorting for a cell.
// strips leading and trailing whitespace.
// this is *not* a generic getInnerText function; it's special to sorttable.
// for example, you can override the cell text with a customkey attribute.
// it also gets .value for <input> fields.
hasInputs = (typeof node.getElementsByTagName == 'function') &&
node.getElementsByTagName('input').length;
if (node.getAttribute("sorttable_customkey") != null) {
return node.getAttribute("sorttable_customkey");
}
else if (typeof node.textContent != 'undefined' && !hasInputs) {
return node.textContent.replace(/^\s+|\s+$/g, '');
}
else if (typeof node.innerText != 'undefined' && !hasInputs) {
return node.innerText.replace(/^\s+|\s+$/g, '');
}
else if (typeof node.text != 'undefined' && !hasInputs) {
return node.text.replace(/^\s+|\s+$/g, '');
}
else {
switch (node.nodeType) {
case 3:
if (node.nodeName.toLowerCase() == 'input') {
return node.value.replace(/^\s+|\s+$/g, '');
}
case 4:
return node.nodeValue.replace(/^\s+|\s+$/g, '');
break;
case 1:
case 11:
var innerText = '';
for (var i = 0; i < node.childNodes.length; i++) {
innerText += sorttable.getInnerText(node.childNodes[i]);
}
return innerText.replace(/^\s+|\s+$/g, '');
break;
default:
return '';
}
}
},
reverse: function(tbody) {
// reverse the rows in a tbody
newrows = [];
for (var i=0; i<tbody.rows.length; i++) {
newrows[newrows.length] = tbody.rows[i];
}
for (var i=newrows.length-1; i>=0; i--) {
tbody.appendChild(newrows[i]);
}
delete newrows;
},
/* sort functions
each sort function takes two parameters, a and b
you are comparing a[0] and b[0] */
sort_numeric: function(a,b) {
aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
if (isNaN(aa)) aa = 0;
bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
if (isNaN(bb)) bb = 0;
return aa-bb;
},
sort_alpha: function(a,b) {
if (a[0]==b[0]) return 0;
if (a[0]<b[0]) return -1;
return 1;
},
sort_ddmm: function(a,b) {
mtch = a[0].match(sorttable.DATE_RE);
y = mtch[3]; m = mtch[2]; d = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt1 = y+m+d;
mtch = b[0].match(sorttable.DATE_RE);
y = mtch[3]; m = mtch[2]; d = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt2 = y+m+d;
if (dt1==dt2) return 0;
if (dt1<dt2) return -1;
return 1;
},
sort_mmdd: function(a,b) {
mtch = a[0].match(sorttable.DATE_RE);
y = mtch[3]; d = mtch[2]; m = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt1 = y+m+d;
mtch = b[0].match(sorttable.DATE_RE);
y = mtch[3]; d = mtch[2]; m = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt2 = y+m+d;
if (dt1==dt2) return 0;
if (dt1<dt2) return -1;
return 1;
},
shaker_sort: function(list, comp_func) {
// A stable sort function to allow multi-level sorting of data
// see: http://en.wikipedia.org/wiki/Cocktail_sort
// thanks to Joseph Nahmias
var b = 0;
var t = list.length - 1;
var swap = true;
while(swap) {
swap = false;
for(var i = b; i < t; ++i) {
if ( comp_func(list[i], list[i+1]) > 0 ) {
var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
swap = true;
}
} // for
t--;
if (!swap) break;
for(var i = t; i > b; --i) {
if ( comp_func(list[i], list[i-1]) < 0 ) {
var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
swap = true;
}
} // for
b++;
} // while(swap)
}
}
/* ******************************************************************
Supporting functions: bundled here to avoid depending on a library
****************************************************************** */
// Dean Edwards/Matthias Miller/John Resig
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", sorttable.init, false);
}
/* for Internet Explorer */
/*#cc_on #*/
/*#if (#_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
sorttable.init(); // call the onload handler
}
};
/*#end #*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
sorttable.init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = sorttable.init;
// written by Dean Edwards, 2005
// with input from Tino Zijdel, Matthias Miller, Diego Perini
// http://dean.edwards.name/weblog/2005/10/add-event/
function dean_addEvent(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
// assign each event handler a unique ID
if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
// create a hash table of event types for the element
if (!element.events) element.events = {};
// create a hash table of event handlers for each element/event pair
var handlers = element.events[type];
if (!handlers) {
handlers = element.events[type] = {};
// store the existing event handler (if there is one)
if (element["on" + type]) {
handlers[0] = element["on" + type];
}
}
// store the event handler in the hash table
handlers[handler.$$guid] = handler;
// assign a global event handler to do all the work
element["on" + type] = handleEvent;
}
};
// a counter used to create unique IDs
dean_addEvent.guid = 1;
function removeEvent(element, type, handler) {
if (element.removeEventListener) {
element.removeEventListener(type, handler, false);
} else {
// delete the event handler from the hash table
if (element.events && element.events[type]) {
delete element.events[type][handler.$$guid];
}
}
};
function handleEvent(event) {
var returnValue = true;
// grab the event object (IE uses a global event object)
event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
// get a reference to the hash table of event handlers
var handlers = this.events[event.type];
// execute each event handler
for (var i in handlers) {
this.$$handleEvent = handlers[i];
if (this.$$handleEvent(event) === false) {
returnValue = false;
}
}
return returnValue;
};
function fixEvent(event) {
// add W3C standard event methods
event.preventDefault = fixEvent.preventDefault;
event.stopPropagation = fixEvent.stopPropagation;
return event;
};
fixEvent.preventDefault = function() {
this.returnValue = false;
};
fixEvent.stopPropagation = function() {
this.cancelBubble = true;
}
// Dean's forEach: http://dean.edwards.name/base/forEach.js
/*
forEach, version 1.0
Copyright 2006, Dean Edwards
License: http://www.opensource.org/licenses/mit-license.php
*/
// array-like enumeration
if (!Array.forEach) { // mozilla already supports this
Array.forEach = function(array, block, context) {
for (var i = 0; i < array.length; i++) {
block.call(context, array[i], i, array);
}
};
}
// generic enumeration
Function.prototype.forEach = function(object, block, context) {
for (var key in object) {
if (typeof this.prototype[key] == "undefined") {
block.call(context, object[key], key, object);
}
}
};
// character enumeration
String.forEach = function(string, block, context) {
Array.forEach(string.split(""), function(chr, index) {
block.call(context, chr, index, string);
});
};
// globally resolve forEach enumeration
var forEach = function(object, block, context) {
if (object) {
var resolve = Object; // default
if (object instanceof Function) {
// functions have a "length" property
resolve = Function;
} else if (object.forEach instanceof Function) {
// the object implements a custom forEach method so use that
object.forEach(block, context);
return;
} else if (typeof object == "string") {
// the object is a string
resolve = String;
} else if (typeof object.length == "number") {
// the object is array-like
resolve = Array;
}
resolve.forEach(object, block, context);
}
};
and the secont script is condition.js
function contition() {
var list = new Array();
list[0] = "calmbfr^<img src='wr-el-calm.png' width='40'>";
list[1] = "---bfr^<img src='wr-el-calm.png' width='40'>";
var j, k, find, item, page, repl;
for (var i=0; i<list.length; i++) {
item = list[i].split("^");
find = item[0];
repl = item[1];
page = document.body.innerHTML;
while (page.indexOf(find) >= 0) {
var j = page.indexOf(find);
var k = find.length;
page = page.substr(0,j) + repl + page.substr(j+k);
document.body.innerHTML = page;
}
}
}
the second script run only with body onload="contition()"
if i run seerate the scripts its ok but when i run together in html and give body onload="contition()" work only the secont script and not the sortable.js
below is the html code
<?php
mysql_connect("localhost", "username", "password") or die("Error connecting to database: ".mysql_error());
/*
localhost - it's location of the mysql server, usually localhost
root - your username
third is your password
if connection fails it will stop loading the page and display an error
*/
mysql_select_db("database") or die(mysql_error());
/* database is the name of database we've created */
?>
<!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" xml:lang="el-gr" lang="el-gr" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="contnow.css" rel="stylesheet"/>
<link href="meteogram_table.css" rel="stylesheet"/>
<script src="sorttable.js" type="text/javascript"></script>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.3.js'></script>
<script>
//<![CDATA[
function contition() {
var list = new Array();
list[0] = "calmbfr^<img src='/ajaxImages/wr-el-calm.png' width='40'>";
list[1] = "---bfr^<img src='/ajaxImages/wr-el-calm.png' width='40'>";
var j, k, find, item, page, repl;
for (var i=0; i<list.length; i++) {
item = list[i].split("^");
find = item[0];
repl = item[1];
page = document.body.innerHTML;
while (page.indexOf(find) >= 0) {
var j = page.indexOf(find);
var k = find.length;
page = page.substr(0,j) + repl + page.substr(j+k);
document.body.innerHTML = page;
}
}
}
//]]>
</script>
</head>
<body onload="contition()"
bgcolor="#CCCCCC">
<div id="menu">
<ul>
<li id="button1"><a href="view_wu_metars_GR.php" title="">
Ελλάδα</a></li>
<li id="button2"><a href="view_wu_metars_NGR.php" title="">
Βόρεια Ελ.</a></li>
<li id="button3"><a href="view_wu_metars_WGR.php" title="">
Δυτικη Ελ.</a></li>
<li id="button4"><a href="view_wu_metars_CGR.php" title="">
Κεντρική Ελ.</a></li>
<li id="button5"><a href="view_wu_metars_SGR.php" title="">
Νότια Ελ.</a></li>
<li id="button6"><a href="view_wu_metars_Islands.php" title="">
Νησιά</a></li>
<li id="button7"><a href="view_wu_metars_Airports.php" title="">
Αεροδρόμια</a></li>
<li id="button8"><a href="view_wu_metars_Balkans.php" title="">
Βαλκάνια</a></li>
</ul>
</div>
<table class='sortable' width="1000px" height="" border="1" bgcolor="#ecf9ff" bordercolor="#008080" style="font-size: 13px;">
<thead bgcolor="#66CCFF">
<tr>
<th>Καιρικές <br> συνθήκες</th>
<th>Περιοχή</th>
<th>Πόλη/ <br> περιοχή</th>
<th style width="110px">Ενημέρωση</th>
<th>Θερμοκρασία <br> (°C)</th>
<th>Υγρασία <br> (%)</th>
<th>Σημείο <br> Δρόσου <br> (°C)</th>
<th>Πίεση <br> (hpa)</th>
<th>Υετός <br> ώρας</th>
<th>Υετός <br> (mm)</th>
<th>Διεύθυνση <br> Ανέμου</th>
<th>Άνεμος <br> (Bfr)</th>
<th>Τύπος <br> Σταθμού</th>
<th><a>Υψό-<br>μετρο<br>m</a></th>
</tr>
</thead>
<tr align='center'>
<?php
$result = mysql_query('SELECT *
FROM wuMETAR_icon_LGTS
ORDER BY id DESC
LIMIT 1;') or die('Invalid query: ' . mysql_error());
//print values to screen
while ($row = mysql_fetch_assoc($result)) {
echo "
<td>---bfr</td>
";
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
<?php
$result = mysql_query('SELECT *
FROM wu_AgionOros_MoniMegistisLavras
ORDER BY id DESC
LIMIT 1;') or die('Invalid query: ' . mysql_error());
//print values to screen
while ($row = mysql_fetch_assoc($result)) {
echo "
<td><b>Άγιον όρος</b></td>
<td><b>Μονή Μεγίστης Λάυρας</b></td>
<td><b style='font-size: 10px;'>".$row['observation_time']."</b></td>
<td style='font-size: 22px; font-weight: bold;'>".$row['temp_c']."</td>
<td style='font-size: 20px; font-weight: bold;'>".$row['relative_humidity']."</td>
<td><b>".$row['dewpoint_c']."</b></td>
<td>".$row['pressure_mb']."</td>
<th>".$row['precip_1hr_metric']."</th>
<td><img width='35px' height='50px' src='/DFS/data/wu/CURRENTXML/mm/".$row['precip_today_metric'].".gif'/></td>
<td><img width='50px' height='50px' src='".$row['wind_dir'].".gif'/></td>
<td><img width='55px' height='55px' src='".$row['wind_mph'].".gif'/></td>
<td><img width='50px' height='50px' src='".$row['station_type'].".gif'/></td>
<td><b>142</b></td>
";
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
</tr>
</body>
</html>
html is bigest but 30000 characters can upload here
my question is how can run this scripts together in html page?
i found the problem is sortable.js run without body onload but the second script need body onload.
can anyone tell me how change the script code for condition.js to work without body onload?
ps: the script condition.js i need to run in the same table with sortable table and i change only the first td of every tr
please help me because the other solution is to create 600000 weather icons but with condition.js is better
thanks
i found a similar solution to work together sortable.js with script to change text to image
$(document).ready(function () {
$("td:contains('40.0clear 0')").html('<img src="/CURRENTXML/Clear.gif" height="40px" width="50px"/>');
});
$(document).ready(function () {
$("td:contains('40.0clear 1.png')").html('<img src="/CURRENTXML/rain.gif" alt="40.0clear 1.png" height="40px" width="50px"/>');
});
$(document).ready(function () {
$("td:contains('2.0clear 1.png')").html('<img src="/CURRENTXML/snow.gif" alt="40.0clear 1.png" height="40px" width="50px"/>');
});

How do i turn this jquery into javascript

Hi I can't use Jquery here. please help me change these 3 selector into javascript.
I already tried document.getElementById('FeedbackLightBox_txtName').value; but i doesn't work.
<script type="text/javascript">
function SetButtonStatus() {
var tb1 = document.getElementById('FeedbackLightBox_txtName').value;
var tb2 = document.getElementById('FeedbackLightBox_txtMessage').value;
var tb3 = document.getElementById('FeedbackLightBox_txtEmail').value;
if (tb1.length >= 5 && tb2.length >= 5 && tb3.length >= 5)
makeBtn();
else
$('#FeedbackLightBox_btnSubmit')[0].control.set_enabled(false);
}
function makeBtn() {
$('#FeedbackLightBox_btnSubmit')[0].control.set_enabled(true);
}
function ClearValues(sender, args) {
$('#FeedbackLightBox_txtName').val('');
$('#FeedbackLightBox_txtMessage').val('');
$('#FeedbackLightBox_txtEmail').val('');
args.set_cancel(true);
return false;
}
</script>
Like this?
document.getElementById('FeedbackLightBox_btnSubmit').control.set_enabled(false);
document.getElementById('FeedbackLightBox_txtName').value = '';
JFYI
When you say
$('#FeedbackLightBox_btnSubmit')[0] // it gives you an access to HTML element object which is equivalent to saying `document.getElementById('Feed..)`.
not sure, where .control.set_enabled(false); is defined on the element, but I guess you do know.
function SetButtonStatus() {
var tb1 = document.getElementById('FeedbackLightBox_txtName').value;
var tb2 = document.getElementById('FeedbackLightBox_txtMessage').value;
var tb3 = document.getElementById('FeedbackLightBox_txtEmail').value;
if (tb1.length >= 5 && tb2.length >= 5 && tb3.length >= 5) {
makeBtn();
} else {
document.getElementById("FeedbackLightBox_btnSubmit").control.set_enabled(false);
}
}
function makeBtn() {
document.getElementById("FeedbackLightBox_btnSubmit").control.set_enabled(true);
}
function ClearValues(sender, args) {
document.getElementById("FeedbackLightBox_txtName").value = '';
document.getElementById("FeedbackLightBox_txtMessage").value = '';
document.getElementById("FeedbackLightBox_txtEmail").value = '';
args.set_cancel(true);
return false;
}
It seems you have a form something like:
<form id="FeedbackLightBox_form" onsubmit="return validate(this)" action="">
Name: <input name="FeedbackLightBox_txtName"><br>
Message: <teaxtArea name="FeedbackLightBox_txtMessage"></textarea><br>
Email: <input name="FeedbackLightBox_txtEmail"><br>
<input type="submit" id="FeedbackLightBox_btnSubmit"> <input type="reset">
</form>
that you want to check something has been entered into each field before submission, so you validate it using:
function validate(form) {
var control, controls = form.controls;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if (control.type != 'submit' && control.value.length < 5) {
return false;
}
}
}
The clearForm function is entlirely unnecessariy if you inlcude a reset button, but anyway:
function clearForm() {
document.getElementById('FeedbackLightBox_form').reset();
}
Similarly, the (inappropriately named) makeBtn function can be:
function makeBtn() {
document.betElementById('FeedbackLightBox_btnSubmit').disabled = false;
}
Maybe it should be called enableBtn?
Looks like jQuery is only used for getting HTML elements so you could define these as global variables before your functions (or pass them as function arguments) to avoid duplication.
var tb1 = document.getElementById('FeedbackLightBox_txtName');
var tb2 = document.getElementById('FeedbackLightBox_txtMessage');
var tb3 = document.getElementById('FeedbackLightBox_txtEmail');
var btn = document.getElementById('FeedbackLightBox_btnSubmit');
function SetButtonStatus() {
if (tb1.value.length >= 5 && tb2.value.length >= 5 && tb3.value.length >= 5)
makeBtn();
else
btn.control.set_enabled(false);
}
function makeBtn() {
btn.control.set_enabled(true);
}
function ClearValues(sender, args) {
tb1.value = '';
tb2.value = '';
tb3.value = '';
args.set_cancel(true);
return false;
}

Retrieving rich text box sharepoint in javascript

I have CustomNewForm for inserting items in the sharepoint list.
The fields are "Reason" and "Reason OverView"; both Multiple Line Rich Text fields. I need to copy some text from "Reason" to "Reason Overview".(A substring)
I tried to get this done with workflow but couldn't find a solution to get a substring of a form field.
I am trying to get the value from "Reason" field in javascript; but unable to do so.
MY CODE :: (not working)
<script type="text/javascript">
function PreSaveAction()
{
var Reason = getTagFromIdentifierAndTitle("textarea","TextField","Reason");
var Original = getTagFromIdentifierAndTitle("textarea","TextField","Reason Overview");
alert('Hi');
Original.innerHTML=Reason.innerHTML;
return true;
}
function getTagFromIdentifierAndTitle(tagName, identifier, title)
{
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++)
{
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len))
{
return tags[i];
}
}
return null;
}
</script>
Any way to get this done??
I solved it using this
<script type="text/javascript">
function PreSaveAction()
{
var Reason = getTagFromIdentifierAndTitle("textarea","TextField","Reason");
var Original = getTagFromIdentifierAndTitle("textarea","TextField","Reason Overview");
var reasonText = RTE_GetEditorDocument(Reason.id);
var reasonOverviewText = reasonText.body.innerText;
if(reasonOverviewText.length>=20)
{
reasonOverviewText = reasonOverviewText.substring(0,20)+'......';
Original.innerText = reasonOverviewText;
}
else
{
Original.innerText = reasonOverviewText;
}
return true;
}
function getTagFromIdentifierAndTitle(tagName, identifier, title)
{
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++)
{
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len))
{
return tags[i];
}
}
return null;
}
</script>

javascript - Failed to load source for: http://localhost/js/m.js

Why oh why oh why... I can't figure out why I keep getting this error. I think I might cry.
/*** common functions */
function GE(id) { return document.getElementById(id); }
function changePage(newLoc) {
nextPage = newLoc.options[newLoc.selectedIndex].value
if (nextPage != "")
{
document.location.href = nextPage
}
}
function isHorizO(){
if (navigator.userAgent.indexOf('iPod')>-1)
return (window.orientation == 90 || window.orientation==-90)? 1 : 0;
else return 1;
}
function ShowHideE(el, act){
if (GE(el)) GE(el).style.display = act;
}
function KeepTop(){
window.scrollTo(0, 1);
}
/* end of common function */
var f = window.onload;
if (typeof f == 'function'){
window.onload = function() {
f();
init();
}
}else window.onload = init;
function init(){
if (GE('frontpage')) init_FP();
else {
if (GE('image')) init_Image();
setTimeout('window.scrollTo(0, 1)', 100);
}
AddExtLink();
}
function AddExtLink(){
var z = GE('extLink');
if (z){
z = z.getElementsByTagName('a');
if (z.length>0){
z = z[0];
var e_name = z.innerHTML;
var e_link = z.href;
var newOption, oSe;
if (GE('PSel')) oSe = new Array(GE('PSel'));
else
oSe = getObjectsByClassName('PSel', 'select')
for(i=0; i<oSe.length; i++){
newOption = new Option(e_name, e_link);
oSe[i].options[oSe[i].options.length] = newOption;
}
}
}
}
/* fp */
function FP_OrientChanged() {
init_FP();
}
function init_FP() {
// GE('orientMsg').style.visibility = (!isHorizO())? 'visible' : 'hidden';
}
/* gallery */
function GAL_OrientChanged(link){
if (!isHorizO()){
ShowHideE('vertCover', 'block');
GoG(link);
}
setTimeout('window.scrollTo(0, 1)', 500);
}
function init_Portfolio() {
// if (!isHorizO())
// ShowHideE('vertCover', 'block');
}
function ShowPortfolios(){
if (isHorizO()) ShowHideE('vertCover', 'none');
}
var CurPos_G = 1
function MoveG(dir) {
MoveItem('G',CurPos_G, dir);
}
/* image */
function init_Image(){
// check for alone vertical images
PlaceAloneVertImages();
}
function Img_OrtChanged(){
//CompareOrientation(arImgOrt[CurPos_I]);
//setTimeout('window.scrollTo(0, 1)', 500);
}
var CurPos_I = 1
function MoveI(dir) {
CompareOrientation(arImgOrt[CurPos_I+dir]);
MoveItem('I',CurPos_I, dir);
}
var arImgOrt = new Array(); // orientation: 1-horizontal, 0-vertical
var aModeName = new Array('Horizontal' , 'Vertical');
var arHs = new Array();
function getDims(obj, ind){
var arT = new Array(2);
arT[0] = obj.height;
arT[1] = obj.width;
//arWs[ind-1] = arT;
arHs[ind] = arT[0];
//**** (arT[0] > arT[1]) = (vertical image=0)
arImgOrt[ind] = (arT[0] > arT[1])? 0 : 1;
// todor debug
if(DebugMode) {
//alert("["+obj.width+","+obj.height+"] mode="+((arT[0] > arT[1])? 'verical' : 'hoziontal'))
writeLog("["+obj.width+","+obj.height+"] mode="+((arT[0] > arT[1])? 'verical' : 'hoziontal')+' src='+obj.src)
}
if (arImgOrt[ind]) {
GE('mi'+ind).className = 'mImageH';
}
}
function CompareOrientation(imgOrt){
var iPhoneOrt = aModeName[isHorizO()];
GE('omode').innerHTML = iPhoneOrt;
//alert(imgOrt == isHorizO())
var sSH = (imgOrt == isHorizO())? 'none' : 'block';
ShowHideE('vertCover', sSH);
var sL = imgOrt? 'H' : 'V';
if (GE('navig')) GE('navig').className = 'navig'+ sL ;
if (GE('mainimage')) GE('mainimage').className = 'mainimage'+sL;
var sPfL = imgOrt? 'Port-<br>folios' : 'Portfolios' ;
if (GE('PortLnk')) GE('PortLnk').innerHTML = sPfL;
}
function SetGetDim( iMInd){
var dv = GE('IImg'+iMInd);
if (dv) {
var arI = dv.getElementsByTagName('img');
if (arI.length>0){
var oImg = arI[0];
oImg.id = 'Img'+iMInd;
oImg.className = 'imageStyle';
//YAHOO.util.Event.removeListener('Img'+iMInd,'load');
YAHOO.util.Event.on('Img'+iMInd, 'load', function(){GetDims(oImg,iMInd);}, true, true);
//oImg.addEventListener('load',GetDims(oImg,iMInd),true);
}
}
}
var occ = new Array();
function PlaceAloneVertImages(){
var iBLim, iELim;
iBLim = 0;
iELim = arImgOrt.length;
occ[0] = true;
//occ[iELim]=true;
for (i=1; i<iELim; i++){
if ( arImgOrt[i]){//horizontal image
occ[i]=true;
continue;
}else { // current is vertical
if (!occ[i-1]){//previous is free-alone. this happens only the first time width i=1
occ[i] = true;
continue;
}else {
if (i+1 == iELim){//this is the last image, it is alone and vertical
GE('mi'+i).className = 'mImageV_a'; //***** expand the image container
}else {
if ( arImgOrt[i+1] ){
GE('mi'+i).className = 'mImageV_a';//*****expland image container
occ[i] = true;
occ[i+1] = true;
i++;
continue;
}else { // second vertical image
occ[i] = true;
occ[i+1] = true;
if (arHs[i]>arHs[i+1]) GE('mi'+(i+1)).style.height = arHs[i]+'px';
i++;
continue;
}
}
}
}
}
//arImgOrt
}
function AdjustWebSiteTitle(){
//if (GE('wstitle')) if (GE('wstitle').offsetWidth > GE('wsholder').offsetWidth) {
if (GE('wstitle')) if (GE('wstitle').offsetWidth > 325) {
ShowHideE('dots1','block');
ShowHideE('dots2','block');
}
}
function getObjectsByClassName(className, eLTag, parent){
var oParent;
var arr = new Array();
if (parent) oParent = GE(parent); else oParent=document;
var elems = oParent.getElementsByTagName(eLTag);
for(var i = 0; i < elems.length; i++)
{
var elem = elems[i];
var cls = elem.className
if(cls == className){
arr[arr.length] = elem;
}
}
return arr;
}
////////////////////////////////
///
// todor debug
var DebugMode = (getQueryVariable("debug")=="1")
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
var sRet = ""
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
sRet = pair[1];
}
}
return sRet
//alert('Query Variable ' + variable + ' not found');
}
var oLogDiv=''
function writeLog(sMes){
if(!oLogDiv) oLogDiv=document.getElementById('oLogDiv')
if(!oLogDiv) {
oLogDiv = document.createElement("div");
oLogDiv.style.border="1px solid red"
var o = document.getElementsByTagName("body")
if(o.length>0) {
o[0].appendChild(oLogDiv)
}
}
if(oLogDiv) {
oLogDiv.innerHTML = sMes+"<br>"+oLogDiv.innerHTML
}
}
First, Firebug is your friend, get used to it. Second, if you paste each function and some supporting lines, one by one, you will eventually get to the following.
var DebugMode = (getQueryVariable("debug")=="1")
function getQueryVariable(variable)
You can't execute getQueryVariable before it is defined, you can create a handle to a future reference though, there is a difference.
There are several other potential issues in your code, but putting the var DebugMode line after the close of the getQueryVariable method should work fine.
It would help if you gave more context. For example, is
Failed to load source for:
http://localhost/js/m.js
the literal text of an error message? Where and when do you see it?
Also, does that code represent the contents of http://localhost/js/m.js? It seems that way, but it's hard to tell.
In any case, the JavaScript that you've shown has quite a few statements that are missing their semicolons. There may be other syntax errors as well. If you can't find them on your own, you might find tools such as jslint to be helpful.
make sure the type attribute in tag is "text/javascript" not "script/javascript".
I know it is more than a year since this question was asked, but I faced this today. I had a
<script type="text/javascript" src="/test/test-script.js"/>
and I was getting the 'Failed to load source for: http://localhost/test/test-script.js' error in Firebug. Even chrome was no loading this script. Then I modified the above line as
<script type="text/javascript" src="/test/test-script.js"></script>
and it started working both in Firefox and chrome. Documenting this here hoping that this will help someone. Btw, I dont know why the later works where as the previous one didn't.

Categories

Resources