How to make dynamic phone number clickable for mobile users - javascript

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+'';
}

Related

Delay for messages in node-telegram-bot-api

I am working on a telegram bot with the node-telegram-bot-api library. I made 2 buttons using keyboard. But when you click on them a lot, the bot will spam and sooner or later it will freeze. Is it possible to somehow put a delay for the user on messages.
if (text === '/start') {
return bot.sendMessage(chatId, 'hello', keyboardMain);
}
export const keyboardMain = {
reply_markup: JSON.stringify({
keyboard: [
[{
text: '/start',
},
],
resize_keyboard: true
})
};
You can create a user throttler using Javascript Map
/*
* #param {number} waitTime Seconds to wait
*/
function throttler(waitTime) {
const users = new Map()
return (chatId) => {
const now = parseInt(Date.now()/1000)
const hitTime = users.get(chatId)
if (hitTime) {
const diff = now - hitTime
if (diff < waitTime) {
return false
}
users.set(chatId, now)
return true
}
users.set(chatId, now)
return true
}
}
How to use:
You'll get the user's chatId from telegram api. You can use that id as an identifier and stop the user for given specific time.
For instance I'm gonna stop the user for 10seconds once the user requests.
// global 10 second throttler
const throttle = throttler(10) // 10 seconds
// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
// reply to user
} else {
// dont reply
}
I tried using this code, put the function code in my function file, connected everything to the required file, and I don’t understand what to do next and where to insert the last code and what to do with it. I'm new to JavaScript and just learning.
import {
bot
} from '../token.js';
import {
throttler
} from '../functions/functions.js';
import {
keyboardMain
} from '../keyboards/keyboardsMain.js';
export function commands() {
bot.on('message', msg => {
const text = msg.text;
const chatId = msg.chat.id;
const throttle = throttler(10);
if (text === '/start') {
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
return bot.sendMessage(chatId, 'hello', keyboardMain);
} else {
// dont reply
}
}
return bot.sendMessage(chatId, 'error');
});
}
Get the time when he pressed the button
Get the time of the next click
Take away the difference and set the condition (if, for example, more than 3 seconds have passed between clicks, then the user will not be frozen).
var token = ""; // FILL IN YOUR OWN TOKEN
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = ""; // FILLINYOUR GOOGLEWEBAPPADDRESS
var ssId = ""; // FILL IN THE ID OF YOUR SPREADSHEET
function getMe() {
var url = telegramUrl + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doGet(e) {
return HtmlService.createHtmlOutput("Hi there");
}
function doPost(e){
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var id = data.message.chat.id;
var msgbegan = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A7").getValue();
var msginfo = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A9").getValue();
var answer = "%0A" + msgbegan + "%0A" ;
///////////////////////
/*
* #param {number} waitTime Seconds to wait
*/
function throttler(waitTime) {
const users = new Map()
return (chatId) => {
const now = parseInt(Date.now()/1000)
const hitTime = users.get(chatId)
if (hitTime) {
const diff = now - hitTime
if (diff < waitTime) {
return false
}
users.set(chatId, now)
return true
}
users.set(chatId, now)
return true
}
}
// global 10 second throttler
const throttle = throttler(500) // 10 seconds
// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
// reply to user
} else {
// dont reply
}
///////////////////////////////////////
if(text == "/start"){
sendText(id, answer);
} else if (text == "/info"){
sendText(id, msginfo);
}else{
if (text.length == 10){
var found = false;
var total_rows = SpreadsheetApp.openById(ssId).getSheets()[0].getMaxRows();
for(i=1; i<=total_rows; i++){
var loop_id = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(i,2).getValue();
if(text == loop_id){
found = true;
found_at = i; // employee row
break;
}
}
if(found){
sendText(id, work_message);
}else{
var msgerrror = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A6").getValue();
var not_found = "%0A" + msgerrror+ "%0A" ;
sendText(id, not_found);
}
} else {
sendText(id, "eroor");
}
}
/////////////
var emp_name = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,1).getValue();
var emp_work = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,3).getValue();
var homeloc = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,4).getValue();
var emp_location = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,8).getValue();
var emp_data = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,5).getValue();
var emp_day = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,6).getValue();
var emp_clock = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,7).getValue();
var emp_location = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,8).getValue();
var welcome = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A2").getValue();
var msgemp = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A3").getValue();
var msgloc = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A4").getValue();
var msgbay = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A5").getValue();
var msghome = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A8").getValue();
var msmobil = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A11").getValue();
var mstoday = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A13").getValue();
var msdata = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A14").getValue();
var msclock = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A15").getValue();
var work_message = welcome + emp_name +
"%0A" + msgemp + emp_work +
"%0A" + mstoday + emp_day +
"%0A" + msdata + emp_data +
"%0A" + msclock + emp_clock +
"%0A" + msghome + homeloc +
"%0A" + msgloc+ emp_location +
"%0A" + msgbay +
"%0A" + msmobil ;
}
Excuse me . I am a beginner
Is this the correct way

Javascript replace string function

I have a script I'm trying to write which takes a string and finds the dmcode then sends it to a function to format it correctly then returns the value. This seems to work but I can't get the replace function to work on the string calling it. This has got to be easy but everything I've tried has resulted in errors.
Your help is appreciated.
Max
function scrubDMC(DM){
var dmcode = DM;
for (var i = 0; i < dmcode.length; i++) {
DMC = dmcode[i];
match = DMC.match(/modelIdentCode="(.*?)"/im);
if (match !== null) {
var modelIdentCode = match[1];
}
match = DMC.match(/systemDiffCode="(.*?)"/im);
if (match !== null) {
var systemDiffCode = match[1];
}
match = DMC.match(/\ssubSystemCode="(.*?)"/im);
if (match !== null) {
var subSystemCode = match[1];
}
match = DMC.match(/subSubSystemCode="(.*?)"/im);
if (match !== null) {
var subSubSystemCode = match[1];
}
}
var sFileName = "DMC-" + modelIdentCode +"-"+ systemDiffCode +"-"+ systemCode + "-" + subSystemCode + subSubSystemCode + "-" + assyCode +"-"+ disassyCode + disassyCodeVariant +"-" + infoCode +infoCodeVariant +"-" +itemLocationCode;
console.log("sFileName : " + sFileName);
return sFileName;
}
Code calling the function that isn't working
var readyWarn2 = readyWarn.replace(/<symbol infoEntityIdent=".*?"\/>/ig, "");
var dmcode = readyWarn2.match(/<dmcode.*?>/ig);
scrubDMC(dmcode);
readyWarn2.replace(dmcode, sFileName);
Your last line needs to be
readyWarn2 = readyWarn2.replace(dmcode, sFileName);
Javascript strings can't be changed, so String.replace() returns a new string value.

How to set a cookie that prevents further javascript alerts?

I have this code for detecting android:
var mobile = (/android/i.test(navigator.userAgent.toLowerCase()));
if (mobile){
alert("Message to android users");
}
...but how do I get that script to also set a cookie so the android user doesn't continue getting the alert (either on reloading the page, returning later to the page, or navigating to other pages which have the alert)?
I also have this, which uses a cookie to avoid a user viewing a "welcome page" they've already seen:
var RedirectURL = "http://www.example.com/real-home-page.html";
var DaysToLive = "365";
var CookieName = "FirstVisit";
function Action() {
location.href = RedirectURL;
}
DaysToLive = parseInt(DaysToLive);
var Value = 'bypass page next time';
function GetCookie() {
var cookiecontent = '';
if(document.cookie.length > 0) {
var cookiename = CookieName + '=';
var cookiebegin = document.cookie.indexOf(cookiename);
var cookieend = 0;
if(cookiebegin > -1) {
cookiebegin += cookiename.length;
cookieend = document.cookie.indexOf(";",cookiebegin);
if(cookieend < cookiebegin) { cookieend = document.cookie.length; }
cookiecontent = document.cookie.substring(cookiebegin,cookieend);
}
}
if(cookiecontent.length > 0) { return true; }
return false;
}
function SetCookie() {
var exp = '';
if(DaysToLive > 0) {
var now = new Date();
then = now.getTime() + (DaysToLive * 24 * 60 * 60 * 1000);
now.setTime(then);
exp = '; expires=' + now.toGMTString();
}
document.cookie = CookieName + '=' + Value + exp;
return true;
}
if(GetCookie() == true) { Action(); }
SetCookie();
Can the second script be adapted and combined into the first to do something like:
function Action() {
don't-open-that-alert-again;
I've googled and found some js cookie scripts, but all over 100K. Prefer something as succinct as the above.

Update/Replace output text onClick - replaceNodes - Javascript

I have a form that takes information and outputs it in a div if its complete. If the form is not complete, output is error messages relating to the specific field which needs correcting. The error messages/output update as information is changed and the button is clicked.
Currently valid output will update as it changes, but going between valid output and error messages, the two sets of text both appear on the page, and then remain there until I refresh the page. Here's the code:
/*
Project 1 - AJAX 2015
2/14/15
Mitch Gundrum
*/
/*
Function to create input and HTML elements,
Create output nodes; output div
*/
function init() {
//Output Div
var div = document.createElement("div");
div.id = "output";
//Name
var name = document.getElementById("name").value;
name.type = "text";
//Address
var address = document.getElementById("address").value;
address.type = "text";
var city = document.getElementById("city").value;
city.type = "text";
var state = document.getElementById("state");
state.type = "text";
var index = state.selectedIndex;
var fullState = state.options[index];
var zip = document.getElementById("zip").value;
zip.type = "text";
//Email
var email = document.getElementById("email").value;
email.type = "text";
//Phone Number
var areaCode = document.getElementById("areaCode").value;
areaCode.type = "text";
var prefix = document.getElementById("prefix").value;
prefix.type = "text";
var suffix = document.getElementById("suffix").value;
suffix.type = "text";
//Gender
var gender = document.getElementsByName("gender");
var genderChoice = "";
for (var i = 0; i < gender.length; i++) {
if (gender[i].checked) {
genderChoice += gender[i].value;
}
}
//Previous Courses
var courses = document.getElementsByName("courses");
var courseChoice = "";
for (var e = 0; e < courses.length; e++) {
if (courses[e].checked) {
courseChoice += courses[e].value + ", ";
}
}
//Call Validate form method; pass all elements
validateForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice);
}
//Check all elements for null
function validateForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice) {
var RUN_OUTPUT = 1;
function br() {
return document.createElement('br');
}
if (name == null || name == "") {
var nameError = "Name is not valid";
var printNameError = document.createTextNode(nameError);
var nameLabel = document.getElementById("nameError");
nameLabel.appendChild(printNameError);
RUN_OUTPUT = 0;
}
if (email == null || email == "") {
var emailError = "Email is not valid";
var printEmailError = document.createTextNode(emailError);
var emailLabel = document.getElementById("emailError");
emailLabel.appendChild(printEmailError);
RUN_OUTPUT = 0;
}
if (areaCode == null || areaCode == "" || prefix == null || prefix == "" || suffix == null || suffix == "") {
var phoneError = "Area Code is not valid";
var printPhoneError = document.createTextNode(phoneError);
var phoneLabel = document.getElementById("phoneError");
phoneLabel.appendChild(printPhoneError);
RUN_OUTPUT = 0;
}
if (address == null || address == "") {
var addressError = "Address is not valid";
var printAddressError = document.createTextNode(addressError);
var addressLabel = document.getElementById("addressError");
addressLabel.appendChild(printAddressError);
RUN_OUTPUT = 0;
}
if (city == null || city == "") {
var cityError = "City is not valid";
var printCityError = document.createTextNode(cityError);
var cityLabel = document.getElementById("cityError");
cityLabel.appendChild(printCityError);
RUN_OUTPUT = 0;
}
if (fullState == null || fullState == "") {
var stateError = "State is not valid";
var printStateError = document.createTextNode(stateError);
var stateLabel = document.getElementById("stateError");
stateLabel.appendChild(printStateError);
RUN_OUTPUT = 0;
}
if (zip == null || zip == "") {
var zipError = "Zip is not valid";
var printZipError = document.createTextNode(zipError);
var zipLabel = document.getElementById("zipError");
zipLabel.appendChild(printZipError);
RUN_OUTPUT = 0;
}
if (genderChoice == null || genderChoice == "") {
var genderError = "Gender is not valid";
var printGenderError = document.createTextNode(genderError);
var genderLabel = document.getElementById("genderError");
genderLabel.appendChild(printGenderError);
RUN_OUTPUT = 0;
}
if (courseChoice == null || courseChoice == "") {
var courseError = "No Courses!";
var printCourseError = document.createTextNode(courseError);
var courseLabel = document.getElementById("courseError");
courseLabel.appendChild(printCourseError);
RUN_OUTPUT = 0;
}
if (Boolean(RUN_OUTPUT) != false) {
document.getElementsByClassName("errorField").textContent = "";
runOutputForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice);
}
}
function runOutputForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice) {
function br() {
return document.createElement('br');
}
var printName = document.createTextNode("Name: " + name + " ");
var printEmail = document.createTextNode("Email: " + email + " ");
var printPhone = document.createTextNode("Phone: " + areaCode + "-" + prefix + "-" + suffix);
var printAddress = document.createTextNode("Address: " + address + " " + city + ", " + fullState.text + " " + zip);
var printGender = document.createTextNode("Gender: " + genderChoice);
var printCourses = document.createTextNode("Courses Taken: " + courseChoice + " ");
div.appendChild(br());
div.appendChild(printName);
div.appendChild(br());
div.appendChild(printEmail);
div.appendChild(br());
div.appendChild(printPhone);
div.appendChild(br());
div.appendChild(printAddress);
div.appendChild(br());
div.appendChild(printGender);
div.appendChild(br());
div.appendChild(printCourses);
div.appendChild(br());
var output = document.getElementById("output");
if (output) {
output.parentNode.replaceChild(div, output);
} else {
document.body.appendChild(div);
}
}
I would like for only the current accurate messages to appear, either errors or valid output, not both. My element-replacing logic seems to be off. I am not using jQuery or innerHTML for this project. Please advise.
jsFiddle

How to add name value pair to existing query string

i need to add new name ,value pair to existing query string when the user click on some button.
i'm using jquery for client side operations.
any idea..?
thank in advance!
You could do:
$('#yourId').click(function(){
var href = window.location.href;
var indexOfCanc = href.indexOf('#');
if(indexOfCanc === -1){
if(href.indexOf('?') === -1){
href+="?newparamter=my";
}else{
href+="&newparamter=my";
}
}else{
var newHref = href.substring(0, indexOfCanc);
var locationHash = href.substring(indexOfCanc);
if(href.indexOf('?') === -1){
newHref += "?newparamter=my"+locationHash;
}else{
newHref += "&newparamter=my"+locationHash;
}
}
//use the new href for example reload the page with the new parameter:
window.location.href = href;
});
Using regExp:
var href = window.location.href,
toAdd,
pattern1 = /\?/gi,
pattern2 = /#/gi;
if (href.match(pattern1) != null) { toAdd = "&" }
else { toAdd = "?" }
toAdd += "param=val";
if (href.match(pattern2) != null) {
var arr = href.split('#');
href = arr[0] + toAdd + '#' + arr[1];
}
else { href += toAdd; }

Categories

Resources