I have checked and tried various solutions provided here previously but still my javascript is not working for the first time. If I refresh the page manually only once, my javascript gets active in a very fine manner.
After refreshing the page, I am very fine with javascript but if I put this same script in other new HTML file then same issue found on loading the page first time.
My script actually search for a text in the HTML file and change the text style every where it is found in that page.
Following is the script that I have used::
<script type="text/javascript">
//<![CDATA[
function Hilitor(id, tag){
var targetNode = document.getElementById(id) || document.body;
var hiliteTag = tag || "EM";
var skipTags = new RegExp("^(?:" + hiliteTag + "|SCRIPT|FORM|SPAN)$");
var colors = ["#ff6", "#a0ffff", "#9f9", "#f99", "#f6f"];
var wordColor = [];
var colorIdx = 0;
var matchRegex = "";
var openLeft = false;
var openRight = false;
// characters to strip from start and end of the input string
var endCharRegex = new RegExp("^[^\\\w]+|[^\\\w]+$", "g");
// characters used to break up the input string into words
var breakCharRegex = new RegExp("[^\\\w'-]+", "g");
this.setMatchType = function(type){
switch(type) {
case "left":
this.openLeft = false;
this.openRight = true;
break;
case "right":
this.openLeft = true;
this.openRight = false;
break;
case "open":
this.openLeft = this.openRight = true;
break;
default:
this.openLeft = this.openRight = false;
}
};
this.setRegex = function(input){
input = input.replace(endCharRegex, "");
input = input.replace(breakCharRegex, "|");
input = input.replace(/^\||\|$/g, "");
if(input) {
var re = "(" + input + ")";
if(!this.openLeft) re = "\\b" + re;
if(!this.openRight) re = re + "\\b";
matchRegex = new RegExp(re, "i");
return true;
}
return false;
};
this.getRegex = function(){
var retval = matchRegex.toString();
retval = retval.replace(/(^\/(\\b)?|\(|\)|(\\b)?\/i$)/g, "");
retval = retval.replace(/\|/g, " ");
return retval;
};
// recursively apply word highlighting
this.hiliteWords = function(node){
if(node === undefined || !node) return;
if(!matchRegex) return;
if(skipTags.test(node.nodeName)) return;
if(node.hasChildNodes()) {
for(var i=0; i < node.childNodes.length; i++)
this.hiliteWords(node.childNodes[i]);
}
if(node.nodeType == 3) { // NODE_TEXT
if((nv = node.nodeValue) && (regs = matchRegex.exec(nv))) {
if(!wordColor[regs[0].toLowerCase()]) {
wordColor[regs[0].toLowerCase()] = colors[colorIdx++ % colors.length];
}
var match = document.createElement(hiliteTag);
match.appendChild(document.createTextNode(regs[0]));
match.style.backgroundColor = wordColor[regs[0].toLowerCase()];
match.style.fontStyle = "inherit";
match.style.fontWeight = "900";
match.style.color = "#000";
var after = node.splitText(regs.index);
after.nodeValue = after.nodeValue.substring(regs[0].length);
node.parentNode.insertBefore(match, after);
}
};
};
// remove highlighting
this.remove = function(){
var arr = document.getElementsByTagName(hiliteTag);
while(arr.length && (el = arr[0])) {
var parent = el.parentNode;
parent.replaceChild(el.firstChild, el);
parent.normalize();
}
};
// start highlighting at target node
this.apply = function(input){
this.remove();
if(input === undefined || !input) return;
if(this.setRegex(input)) {
this.hiliteWords(targetNode);
}
};
}
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var query = getParameterByName('query');
var myHilitor = new Hilitor("spnId");
myHilitor.apply(query);
//]]>
</script>
Related
How can I add a text field to all even pages of a pdf document?
With the following the text is added only to the second page of the document.
if ( fld = "undefined" ) {
var f = this.addField("MacroDate", "text", 1, [550,0,50,15]);
f.delay = true;
f.alignment = "center";
f.fillColor = color.transparent;
f.lineWidth = 0;
f.strokeColor = color.black;
f.borderStyle = border.s;
f.textSize = 8;
f.textColor = color.black;
f.textFont = font.Helv;
f.readonly = false;
f.multiline = false;
f.doNotScroll = true;
f.value = util.printd("dd/mm/yyyy", new Date());
f.delay = false;
} ```
I want to send prodName and prodItem into a URL that will be captured by product.html so when a user clicks on a product (index.html), a URL will be created and that URL will be used but on product.html. I want to catch prodName and proItem and put the text in the product.html but the value will be null.
index.html
$(".product-item").each(function(index, value) {
var prodName = $(this).children("h2").attr("data-prodname");
var prodItem = $(this).children("h2").attr("data-proditem");
var link = $("<a href='product.html?prodName=" + prodName + "&prodItem=" + prodItem + "'/>");
console.log(prodName);
console.log(prodItem);
$(this).children("img").wrap(link);
});
})
product.html
$.urlParam = function (parameterName) {
var results = new RegExp('[\?&]' + parameterName + '=([^&#]*)').exec(window.location.href);
if (results === null) {
return null;
} else {
return decodeURI(results[1]) || 0;
}
}
var adminSerial = $.urlParam('ProdName');
var dashboardName = $.urlParam('ProdItem');
$('#product').html("The text is " + adminSerial);
I put this code on pruduct.html and now it works.
var getParams = function (url) {
var params = {};
var parser = document.createElement('a');
parser.href = url;
var query = parser.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
params[pair[0]] = decodeURIComponent(pair[1]);
}
return params;
};
var mylocation ={};
var mylocation = getParams(window.location.href);
console.log(mylocation.prodName);
$('#product').html(mylocation.prodName);
$('#item').html(mylocation.prodItem);
I am running into an issue with splitting a string into an array. To help myself troubleshoot the problem, I included two alert() functions, but only one gets called. Therefore, I know that there is an issue splitting a string into an array (for a basic username/password check). Here is my JS code:
function check() {
var user = document.loginform.usr.value;
var pass = document.loginform.psw.value;
var valid = false;
var txt = new XMLHttpRequest();
var alltext = "";
var allLines = [];
var usrn = [];
var pswd = [];
txt.open("GET", "/c.txt", true);
alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
alert("usrn split");
pswd = allLines[1].split(',');
alert("pswd split");
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
The file that contains the login credentials (c.txt) is as follows:
User1,User2
pass,password
When User1 enters his/her name into the form, the password should be "pass". However, the script gets stopped at "pswd = allLines[1].split(',');". Am I misunderstanding the lines array?
Any help is appreciated - thanks!
You need to either use a synchronous call by changing the line to
txt.open("GET", "/c.txt", false);
Or use the "onreadystatechange" event to get the response when the server returns it
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
alert("usrn split");
pswd = allLines[1].split(',');
alert("pswd split");
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
}
You need to call txt.send(). Also it is async so txt.responseText will most likely be null.
You can use onreadystatechanged like so to ensure that txt.responseText has a value:
txt.onreadystatechange = function() {
if (txt.readyState == 4) { // 4 = DONE
alert(txt.responseText);
}
}
Okay - after fiddling with the code and doing some more research, I got a working script. This script takes data from a form and checks it against a file (c.txt). If the form entries match a username/password combination in c.txt, it takes you to another webpage.
function check() {
var user = document.loginform.usr.value;
var pass = document.loginform.psw.value;
var valid = false;
var txt;
if(window.XMLHttpRequest){
txt = new XMLHttpRequest();
}else{
txt = new ActiveXObject("Microsoft.XMLHTTP");
}
var allLines = [];
var usrn = [];
var pswd = [];
txt.onreadystatechange=function() {
if(txt.readyState==4 && txt.status==200){
var alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
pswd = allLines[1].split(',');
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
}
txt.open("GET", "c.txt", false);
txt.send();
}
I have phone numbers on my website that are automatically inserted via a JavaScript to display either a default phone number (that's defined within the primary JavaScript) or change to a variable phone number if the webpage is accessed by a URL string with the phone number in it - for example:
http:www.website.com?tfid=8005551212
What I need to do is make the phone numbers clickable for mobile users so that whichever phone number appears they can click it and it will call the phone number.
I understand that if you wrap the phone number with an anchor with the tel: attribute it will launch the click-to-call function, but how can the tag be written so it will allow for the phone number variable to be passed? ex:
variable telephone number
Do you mean this?
Please rewrite your script to not use document.write. If you ever call one of your functions after the page loaded it will wipe the page.
document.getElementById("phonenumber").innerHTML=''+phone_number+'';
Like this, using your original code
<div id="phonenumber">Call: </div>
function getPhone() {
var phone = get_named_cookie("MM_TrackableNumber");
if (phone == null) phone = "8885551313";
return formatnumber(phone);
}
window.onload=function() {
document.getElementById("phonenumber").innerHTML+=getPhone();
}
Full code
function pixelfire(debug) {
var phone_number = getVar("phone_number");
var keyword = getVar("keyword");
var source = getVar("source");
if (keyword) {
setcookie(keyword, phone_number);
} else {
var keyword = get_named_cookie("MM_Keyword");
var phone_number = get_named_cookie("MM_TrackableNumber");
return keyword || null;
}
var campaign = getVar("campaign");
var content = getVar("content");
var url = "http://www.mongoosemetrics.com/pixelfire.php?phone_number=" + phone_number;
var url = url + "&keyword=" + keyword;
var url = url + "&source=" + source;
var url = url + "&campaign=" + campaign;
var url = url + "&content=" + content;
myImage = new Image();
myImage.src = url;
}
function setcookie(key, tn, path) {
index = -1;
var today = new Date();
today.setTime(today.getTime());
var cookie_expire_date = new Date(today.getTime() + (365 * 86400000));
document.cookie = "MM_TrackableNumber=" + tn + ";path=/;expires=" + cookie_expire_date.toGMTString();
document.cookie = "MM_Keyword=" + key + ";path=/;expires=" + cookie_expire_date.toGMTString();
}
function getPhone() {
var phone = get_named_cookie("MM_TrackableNumber");
if (phone == null) phone = "8885551313";
return formatnumber(phone);
}
function get_named_cookie(name) {
if (document.cookie) {
index = document.cookie.indexOf(name);
if (index != -1) {
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {
nameend = document.cookie.length;
}
var ret_one = document.cookie.substring(namestart, nameend);
return ret_one;
}
}
}
//function to format the phonenumber to (123) 456-7890
function formatnumber(num) {
_return = "1-";
var ini = num.substring(0, 3);
_return += ini + "-";
var st = num.substring(3, 6);
_return += st + "-";
var end = num.substring(6, 10);
_return += end;
return _return;
}
function getVar(name) {
get_string = document.location.search;
return_value = '';
do { //This loop is made to catch all instances of any get variable.
name_index = get_string.indexOf(name + '=');
if (name_index != -1) {
get_string = get_string.substr(name_index + name.length + 1, get_string.length - name_index);
end_of_value = get_string.indexOf('&');
if (end_of_value != -1) value = get_string.substr(0, end_of_value);
else value = get_string;
if (return_value == '' || value == '') return_value += value;
else return_value += ', ' + value;
}
} while (name_index != -1)
//Restores all the blank spaces.
space = return_value.indexOf('+');
while (space != -1) {
return_value = return_value.substr(0, space) + ' ' + return_value.substr(space + 1, return_value.length);
space = return_value.indexOf('+');
}
return (return_value);
}
window.onload = function () {
key = getVar("keyword");
tn = getVar("tfid");
source = getVar("source");
content = getVar("content");
campaign = getVar("campaign");
if (tn != "") {
setcookie(key, tn);
}
var phone_number = getPhone();
document.getElementById("phonenumber").innerHTML+=''+phone_number+'';
}
So I'm creating a widget for the iPhone lockscreen using CSS/HTML. I can't figure out how to keep the weather info from disappearing when the phone screen turns off after a minute or when the phone is offline. Any tips? Here's the code:
<script type="text/javascript">
var iconExtWall = '.png'
var iconExtLock = '.png'
var locale = 'Beirut, Lebanon'
var iconSetWall = 'stardock'
var iconSetLock = 'stardock'
var enableWallpaper = true
var isCelsius = true
var useRealFeel = false
var enableLockScreen = true
var source = 'appleAccuweatherStolen'
var stylesheetWall = 'mini'
var stylesheetLock = 'Under_StatusBar'
var updateInterval = 15
var postal;
var demoMode = false;
var enabled;
if (location.href.indexOf("Wallpaper") > 0){
stylesheet = stylesheetLock;
iconSet = iconSetLock;
iconExt = iconExtLock;
enabled = enableLockScreen;
}else{
stylesheet = stylesheetWall;
iconSet = iconSetWall;
iconExt = iconExtWall;
enabled = enableWallpaper;
}
if(enabled == true){
if(iconSet == null || iconSet == 'null' || iconSet == ""){
var iconSet = stylesheet;
}
var headID = document.getElementsByTagName("head")[0];
var styleNode = document.createElement('link');
styleNode.type = 'text/css';
styleNode.rel = 'stylesheet';
styleNode.href = 'Stylesheets/'+stylesheet+'.css';
headID.appendChild(styleNode);
var scriptNode = document.createElement('script');
scriptNode.type = 'text/javascript';
scriptNode.src = 'Sources/'+source+'.js';
headID.appendChild(scriptNode);
}
function onLoad(){
if (enabled == true){
if (demoMode == true){
document.getElementById("weatherIcon").src="IconSets/"+iconSet+"/"+"cloudy1"+iconExt;
document.getElementById("city").innerText="Somewhere";
document.getElementById("desc").innerText="Partly Cloudy";
document.getElementById("temp").innerText="100�";
document.getElementById("forecast").innerText="Sun";
}else{
document.getElementById("weatherIcon").src="IconSets/"+iconSet+"/"+"dunno"+iconExt;
validateWeatherLocation(escape(locale).replace(/^%u/g, "%"), setPostal)
}
}else{
document.getElementsByTagName("body")[0].innerText='';
}
}
function convertTemp(num)
{
if (isCelsius == true)
return Math.round ((num - 32) * 5 / 9);
else
return num;
}
function setPostal(obj){
if (obj.error == false){
if(obj.cities.length > 0){
postal = escape(obj.cities[0].zip).replace(/^%u/g, "%")
document.getElementById("WeatherContainer").className = "";
weatherRefresherTemp();
}else{
document.getElementById("city").innerText="Not Found";
document.getElementById("WeatherContainer").className = "errorLocaleNotFound";
}
}else{
document.getElementById("city").innerText=obj.errorString;
document.getElementById("WeatherContainer").className = "errorLocaleValidate";
setTimeout('validateWeatherLocation(escape(locale).replace(/^%u/g, "%"), setPostal)', Math.round(1000*60*5));
}
}
function dealWithWeather(obj){
var translatedesc="description";
if (obj.error == false){
document.getElementById("city").innerText=obj.city;
document.getElementById("city2").innerText=obj.city;
document.getElementById("desc").innerText=obj.description.toLowerCase();
if(useRealFeel == true){
tempValue = convertTemp(obj.realFeel);
}else{
tempValue = convertTemp(obj.temp)
}
document.getElementById("temp").innerText=tempValue+"º";
document.getElementById("weatherIcon").src="IconSets/"+iconSet+"/"+MiniIcons[obj.icon]+iconExt;
/*ProductRed*/
lastResults = new Array;
lastResults[0] = {daycode:obj.daycode, icon:obj.icon, hi:obj.hi, lo:obj.lo, now:obj.temp};
var c = obj.forecast.length;
var titi = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
var toto =new Date();
var tutu = toto.getDay();
var tata;
if (c > 6) c = 6; // just to be safe
for (var i=0; i<c; ++i)
{
var forecast = obj.forecast[i];
tata = tutu + i;
if(tata > 6) {tata = tata - 7;}
document.getElementById('day'+i).innerText = titi[tata];
document.getElementById('hi'+i).innerHTML = convertTemp(forecast.hi)+'° ';
document.getElementById('low'+i).innerHTML= convertTemp(forecast.lo)+'° ';
document.getElementById('wIcon'+i).src="IconSets/"+iconSet+"/"+MiniIcons[forecast.icon]+iconExt;
lastResults[i+1] = {daycode:forecast.daycode, icon:forecast.icon, hi:forecast.hi, lo:forecast.lo};
}
/*ProductRed*/
document.getElementById("WeatherContainer").className = "";
}else{
//Could be down to any number of things, which is unhelpful...
document.getElementById("WeatherContainer").className = "errorWeatherDataFetch";
}
var this_date_timestamp = new Date()
var this_weekday = this_date_timestamp.getDay()
var this_date = this_date_timestamp.getDate()
var this_month = this_date_timestamp.getMonth()
var this_year = this_date_timestamp.getYear()
if (this_year < 1000)
this_year+= 1900;
if (this_year==101)
this_year=2001;
}
function weatherRefresherTemp(){ //I'm a bastard ugly hack. Hate me.
fetchWeatherData(dealWithWeather,postal);
setTimeout(weatherRefresherTemp, 60*1000*updateInterval);
}
Thanks!