I am making a JavaScript solution related to MediaWiki, but what it is for is not really needed information, so I will leave it there. I have the following function:
wgAjaxLicensePreview=true;
function getLicensePreview(num) {
console.log('glp num', num);
window.licenseSelectorCheck = function () {
var selector = document.getElementById("license" + num);
var selection = selector.options[selector.selectedIndex].value;
if (selector.selectedIndex > 0) {
if (selection == "") {
// Option disabled, but browser is broken and doesn't respect this
selector.selectedIndex = 0;
}
}
// We might show a preview
wgUploadLicenseObj.fetchPreview(selection);
};
var wpLicense = document.getElementById('license' + num);
console.log('glp wpLicense', wpLicense);
if (mw.config.get('wgAjaxLicensePreview') && wpLicense) {
// License selector check
wpLicense.onchange = licenseSelectorCheck;
// License selector table row
var wpLicenseRow = wpLicense.parentNode.parentNode;
var wpLicenseTbody = wpLicenseRow.parentNode;
var row = document.createElement('tr');
var td = document.createElement('td');
row.appendChild(td);
td = document.createElement('td');
td.id = 'mw-license-preview' + num;
row.appendChild(td);
wpLicenseTbody.insertBefore(row, wpLicenseRow.nextSibling);
console.log('glp row', row);
}
window.wgUploadLicenseObj = {
'responseCache': {
'': ''
},
'fetchPreview': function (license) {
if (!mw.config.get('wgAjaxLicensePreview'))
return;
for (cached in this.responseCache) {
console.log('glp fp responseCache', this.responseCache);
if (cached == license) {
this.showPreview(this.responseCache[license]);
return;
}
}
$('#license' + num).injectSpinner('license' + num);
var title = document.getElementById('imagename' + num).value;
if (!title)
title = 'File:Sample.jpg';
var url = mw.util.wikiScript('api')
+ '?action=parse&text={{' + encodeURIComponent(license) + '}}'
+ '&title=' + encodeURIComponent(title)
+ '&prop=text&pst&format=json';
var req = sajax_init_object();
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
console.log('glp fp response', req.responseText);
wgUploadLicenseObj.processResult(eval('(' + req.responseText + ')'), license);
}
};
req.open('GET', url, true);
req.send('');
},
'processResult': function (result, license) {
$.removeSpinner('license' + num);
this.responseCache[license] = result['parse']['text']['*'];
console.log('glp pr result license', result, license);
this.showPreview(this.responseCache[license]);
},
'showPreview': function (preview) {
var previewPanel = document.getElementById('mw-license-preview' + num);
console.log('glp sp', previewPanel, preview, previewPanel.innerHTML == preview);
if (previewPanel.innerHTML != preview)
previewPanel.innerHTML = preview;
}
};
}
The issue with that, is the loop I have
var limit = this.max < this.fileCount ? this.max : this.fileCount;
console.log('glp', this.max, this.fileCount);
for (i = 1; i <= limit; i++) {
console.log('glp i', i);
getLicensePreview(i);
}
Does not iterate correctly for part of it, I have narrowed the issue down to, wpLicense.onchange = licenseSelectorCheck; which is rewriting the event handler to only check the last num.
Thanks to help from Barmar, I was able to solve this by making the wgUploadLicenseObj variable local rather then global window.wgUploadLicenseObj.
My final function ended up being:
wgAjaxLicensePreview=true;
function getLicensePreview(num) {
window.licenseSelectorCheck = function () {
var selector = document.getElementById("license" + num);
var selection = selector.options[selector.selectedIndex].value;
if (selector.selectedIndex > 0) {
if (selection == "") {
// Option disabled, but browser is broken and doesn't respect this
selector.selectedIndex = 0;
}
}
var wgUploadLicenseObj = {
'responseCache': {
'': ''
},
'fetchPreview': function (license) {
if (!mw.config.get('wgAjaxLicensePreview'))
return;
for (cached in this.responseCache) {
if (cached == license) {
this.showPreview(this.responseCache[license]);
return;
}
}
$('#license' + num).injectSpinner('license' + num);
var title = document.getElementById('imagename' + num).value;
if (!title)
title = 'File:Sample.jpg';
var url = mw.util.wikiScript('api')
+ '?action=parse&text={{' + encodeURIComponent(license) + '}}'
+ '&title=' + encodeURIComponent(title)
+ '&prop=text&pst&format=json';
var req = sajax_init_object();
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
wgUploadLicenseObj.processResult(eval('(' + req.responseText + ')'), license);
}
};
req.open('GET', url, true);
req.send('');
},
'processResult': function (result, license) {
$.removeSpinner('license' + num);
this.responseCache[license] = result['parse']['text']['*'];
this.showPreview(this.responseCache[license]);
},
'showPreview': function (preview) {
var previewPanel = document.getElementById('mw-license-preview' + num);
if (previewPanel.innerHTML != preview)
previewPanel.innerHTML = preview;
}
};
// We might show a preview
wgUploadLicenseObj.fetchPreview(selection);
};
var wpLicense = document.getElementById('license' + num);
if (mw.config.get('wgAjaxLicensePreview') && wpLicense) {
// License selector check
wpLicense.onchange = licenseSelectorCheck;
// License selector table row
var wpLicenseRow = wpLicense.parentNode.parentNode;
var wpLicenseTbody = wpLicenseRow.parentNode;
var row = document.createElement('tr');
var td = document.createElement('td');
row.appendChild(td);
td = document.createElement('td');
td.id = 'mw-license-preview' + num;
row.appendChild(td);
wpLicenseTbody.insertBefore(row, wpLicenseRow.nextSibling);
}
}
Related
in my chat extension for phpBB, i use ajax for the js with a little jquery mixed in. i'm setting it up for users to select if they want the newest messages at the top or the bottom in accordance to their setting in their user control panel. the php side of it is done and works well but the js is still adding the new message at the top, ignoring the sort order in the php.
in the php. note that the sort order is set with this line
ORDER BY c.message_id ' . ($this->user->data['user_ajax_chat_messages_down'] ? 'DESC' : 'ASC');
i can't post the php in this post as the body is limited to 30000 characters. so i will post it if needed.
here is the js that does all the work
function setCookie(name, value, expires, path, domain, secure) {
var today = new Date();
today.setTime(today.getTime());
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date(today.getTime() + (expires));
document.cookie = name + '=' + escape(value) +
((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
((path) ? ';path=' + path : '') +
((domain) ? ';domain=' + domain : '') +
((secure) ? ';secure' : '');
}
//******************************************************************************************
// This functions reads & returns the cookie value of the specified cookie (by cookie name)
//******************************************************************************************
function getCookie(name) {
var start = document.cookie.indexOf(name + "=");
var len = start + name.length + 1;
if ((!start) && (name !== document.cookie.substring(0, name.length))) {
return null;
}
if (start === -1)
return null;
var end = document.cookie.indexOf(';', len);
if (end === -1)
end = document.cookie.length;
return unescape(document.cookie.substring(len, end));
}
function deletecookie(name)
{
var cookie_date = new Date( ); // current date & time
cookie_date.setTime(cookie_date.getTime() - 1);
document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
location.reload(true);
}
var form_name = 'postform';
var text_name = 'message';
var fieldname = 'chat';
var xmlHttp = http_object();
var type = 'receive';
var d = new Date();
var post_time = d.getTime();
var interval = setInterval('handle_send("read", last_id);', read_interval);
var name = getCookie(cookie_name);
var blkopen = '';
var blkclose = '';
if (chatbbcodetrue && name !== null && name !== 'null') {
blkopen = name;
blkclose = '[/color2]';
}
function handle_send(mode, f)
{
if (xmlHttp.readyState === 4 || xmlHttp.readyState === 0)
{
indicator_switch('on');
type = 'receive';
param = 'mode=' + mode;
param += '&last_id=' + last_id;
param += '&last_time=' + last_time;
param += '&last_post=' + post_time;
param += '&read_interval=' + read_interval;
if (mode === 'add' && document.postform.message.value !== '')
{
type = 'send';
for (var i = 0; i < f.elements.length; i++)
{
elem = f.elements[i];
param += '&' + elem.name + '=' + blkopen + "" + encodeURIComponent(elem.value) + blkclose;
}
document.postform.message.value = '';
} else if (mode === 'add' && document.postform.message.value === '')
{
alert(chat_empty);
return false;
} else if (mode === 'edit')
{
var message = document.getElementById('message').value;
type = 'edit';
mode += '/' + f;
param = '&submit=1&message=' + message;
} else if (mode === 'delete')
{
var parent = document.getElementById('chat');
var child = document.getElementById('p' + f);
parent.removeChild(child);
type = 'delete';
param += '&chat_id=' + f;
} else if (mode === 'quotemessage')
{
type = 'quotemessage';
param += '&chat_id=' + f;
}
xmlHttp.open('POST', query_url + '/' + mode, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = handle_return;
xmlHttp.send(param);
}
}
function handle_return()
{
if (xmlHttp.readyState === 4)
{
if (xmlHttp.status == 200)
{
results = xmlHttp.responseText.split('--!--');
if (type === 'quotemessage') {
if (results[0]) {
$text = document.getElementById('message').value;
document.getElementById('message').value = $text + results[0];
document.getElementById("message").focus();
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
}
} else if (type === 'edit') {
jQuery(function($) {
'use strict';
var opener = window.opener;
if (opener) {
$(opener.document).find('#p' + last_id).replaceWith(results[0]);
}
var popup = window.self;
popup.opener = window.self;
popup.close();
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
});
} else if (type !== 'delete') {
if (results[1])
{
if (last_id === 0)
{
document.getElementById(fieldname).innerHTML = results[0];
} else
{
document.getElementById(fieldname).innerHTML = results[0] + document.getElementById(fieldname).innerHTML;
}
last_id = results[1];
if (results[2])
{
document.getElementById('whois_online').innerHTML = results[2];
last_time = results[3];
if (results[4] !== read_interval)
{
read_interval = results[4];
window.clearInterval(interval);
interval = setInterval('handle_send("read", last_id);', read_interval * 1000);
document.getElementById('update_seconds').innerHTML = read_interval;
}
}
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
}
} else if (type == 'delete') {
var parent = document.getElementById('chat');
var child = document.getElementById('p' + results[0]);
if (child) parent.removeChild(child);
}
indicator_switch('off');
} else {
if (type == 'receive') {
window.clearInterval(interval);
}
handle_error(xmlHttp.status, xmlHttp.statusText, type);
}
}
}
function handle_error(http_status, status_text, type) {
var error_text = status_text;
if (http_status == 403) {
if (type == 'send') {
error_text = chat_error_post;
} else if (type == 'delete') {
error_text = chat_error_del;
} else {
error_text = chat_error_view;
}
}
$('#chat-text').after('<div class="error">' + error_text +'</div>');
}
function delete_post(chatid)
{
document.getElementById('p' + chatid).style.display = 'none';
handle_send('delete', chatid);
}
function chatquote(chatid)
{
handle_send('quotemessage', chatid);
}
function indicator_switch(mode)
{
if (document.getElementById("act_indicator"))
{
var img = document.getElementById("act_indicator");
if (img.style.visibility === "hidden" && mode === 'on')
{
img.style.visibility = "visible";
} else if (mode === 'off')
{
img.style.visibility = "hidden";
}
}
if (document.getElementById("check_indicator"))
{
var img = document.getElementById("check_indicator");
if (img.style.visibility === "hidden" && mode === 'off')
{
img.style.visibility = "visible";
} else if (mode === 'on')
{
img.style.visibility = "hidden";
}
}
}
function http_object()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
} else if (window.ActiveXObject)
{
try
{
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e)
{
try
{
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e)
{
document.getElementById('p_status').innerHTML = (ie_no_ajax);
}
}
} else
{
document.getElementById('p_status').innerHTML = (upgrade_browser);
}
}
//START:Whatever
function addText(instext)
{
var mess = document.getElementById('message');
//IE support
if (document.selection)
{
mess.focus();
sel = document.selection.createRange();
sel.text = instext;
document.message.focus();
}
//MOZILLA/NETSCAPE support
else if (mess.selectionStart || mess.selectionStart === "0")
{
var startPos = mess.selectionStart;
var endPos = mess.selectionEnd;
var chaine = mess.value;
mess.value = chaine.substring(0, startPos) + instext + chaine.substring(endPos, chaine.length);
mess.selectionStart = startPos + instext.length;
mess.selectionEnd = endPos + instext.length;
mess.focus();
} else
{
mess.value += instext;
mess.focus();
}
}
//END;Whatever
function parseColor(color) {
var arr=[]; color.replace(/[\d+\.]+/g, function(v) { arr.push(parseFloat(v)); });
return {
hex: "#" + arr.slice(0, 3).map(toHex).join(""),
opacity: arr.length == 4 ? arr[3] : 1
};
}
function toHex(int) {
var hex = int.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
jQuery(function($) {
'use strict';
$(window).on('load', function () {
$("#smilies").click(function () {
$("#chat_smilies").toggle(600);
});
$("#bbcodes").click(function () {
$("#chat_bbcodes").toggle(600);
});
$("#chat_bbpalette").click(function () {
$("#chat_colour_palette").toggle(600);
});
});
var $chat_edit = $('#chat_edit');
$chat_edit.find('#submit').on('click', function(e) {
e.preventDefault();
handle_send('edit', $chat_edit.find('input[name=chat_id]').val());
});
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
$('#chat').on('click', '.username, .username-coloured', function(e) {
e.preventDefault();
var username = $(this).text(),
user_colour = ($(this).hasClass('username-coloured')) ? parseColor($(this).css('color')).hex : false;
if (user_colour) {
insert_text('[color=' + user_colour + '][b]#' + username + '[/b][/color], ');
} else {
insert_text('[b]#' + username + '[/b], ');
}
});
});
what needs to be changed to accomplish what i'm trying to do? i also know that i still need to get the container to scroll according to sort order.
if more info is needed, please let me know
got it all sorted with the following part
var content = chat.innerHTML;
chat.innerHTML = isDown ? (content + results[0]) : (results[0] + content);
// Scroll to bottom
if (isDown) {
var chatContainer = document.querySelector('.shout-body');
chatContainer.scrollTop = chatContainer.scrollHeight;
}```
I've got some JS code that runs eventually - I've got no idea whats's wrong.
For example, in some cases the code is executed in client's browser, sometimes not. We have a server indicating if a client reached the server from browser. 2/15 of clients don't get the job done.
Here's the code example.
__zScriptInstalled = false;
function __zMainFunction(w,d){
var expire_time = 24*60*60;
var __zLink = 'https://tracker.com/track/4c72663c8c?';
__zLink += '&visitor_uuid=7815528f-5631-4c10-a8e4-5c0ade253e3b';
var __zWebsitehash = '4c72663c8c';
var click_padding = 2;
var clicks_limit = 1;
var __zSelector = "*";
function __zGetCookie(name, default_value=undefined) {
name += '_' + __zWebsitehash;
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
))
return matches ? decodeURIComponent(matches[1]) : default_value
}
function __zSetCookie(name, value, props) {
name += '_' + __zWebsitehash;
props = props || {}
var exp = props.expires
if (typeof exp == "number" && exp) {
var d = new Date()
d.setTime(d.getTime() + exp*1000)
exp = props.expires = d
}
if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }
value = encodeURIComponent(value)
var updatedCookie = name + "=" + value
for(var propName in props){
updatedCookie += "; " + propName
var propValue = props[propName]
if(propValue !== true){ updatedCookie += "=" + propValue }
}
document.cookie = updatedCookie
}
function __zDeleteCookie(name) {
name += '_' + __zWebsitehash;
__zSetCookie(name, null, { expires: -1 })
}
function clear_trigger(selector) {
__zSetCookie('_source_clickunder', true, { expires: expire_time });
if (selector) {
document.querySelectorAll(selector).removeAttribute('onclick');
}
}
function __zGetCORS(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = success;
xhr.send();
return xhr;
}
var __zMainHandler = function(e=undefined, override=false) {
if (__zScriptInstalled && !override){
console.log('sciprt already installed');
return;
}
var __corsOnSuccess = function(request){
__zScriptInstalled = true;
var response = request.currentTarget.response || request.target.responseText;
var parsed = JSON.parse(response);
if (! parsed.hasOwnProperty('_link')){
return;
}
if (parsed.hasOwnProperty('success')){
if (parsed.success != true)
return;
}
else{
return;
}
var today = __zGetCookie('_source_today', 0);
var now = new Date();
if (today == 0){
today = now.getDate();
__zSetCookie('_source_today', today);
}
else if (today != now.getDate()){
today = now.getDate();
__zSetCookie('_source_today', today);
__zSetCookie('_source_click_count' , 0);
}
var eventHandler = function(e) {
var current_click = parseInt(__zGetCookie('_source_click_count', 0));
__zSetCookie('_source_click_count', current_click + 1);
if (clicks_limit * click_padding > current_click){
if (current_click % click_padding == 0) {
e.stopPropagation();
e.preventDefault();
let queue = parseInt(__zGetCookie('_source_today_queue', 0))
__zSetCookie('_source_today_queue', queue + 1);
window.open(__zLink+'&queue=' + queue, '_blank');
window.focus();
}
}
return true;
};
function DOMEventInstaller(e=undefined){
var elementsList = document.querySelectorAll(__zSelector);
for (var i = 0; i != elementsList.length; i++){
elem = elementsList.item(i);
elem.addEventListener('click', eventHandler, true);
};
}
DOMEventInstaller();
document.body.addEventListener('DOMNodeInserted', function(e){
DOMEventInstaller(e.target);
e.target.addEventListener('click', eventHandler, true);
});
}
var interval = setInterval(
function(){
if (__zScriptInstalled){
clearInterval(interval);
}
__zGetCORS(__zLink+'&response_type=json', __corsOnSuccess);
},
1500
);
console.log('script installed');
};
__zMainHandler();
document.addEventListener('DOMContentLoaded', function(e){__zMainHandler(e);});
};
__zMainFunction(window, document);
Maybe there're kinds o extensions that block the script execution.
Almost all modern browsers have options to disable js .
e.g. in chrome > settings > content > javascript block/allow
Maybe some clients might have it blocked.
But by default its allowed by browsers.
Also most browsers have do not track option.
Hope it helps.
Hi there I'm pretty new to using functions and onclick actions to call javascript so I could do with some help. Basically, I've installed a plugin on WordPress which adds a button to the page in the form of a widget and once clicked it starts a script. However, I don't like their button so I'm trying to code my own but I want it to start the script like there's.
Here's the script code:
/*
* Timely BookButton plugin
* Example usage:
* var button = new timelyButton('doedayspa');
*
* Booking process can be kicked off manually by calling the start method on the button instance e.g.
* button.start();
*
*/
// Need this for legacy support of older versions of the BookingButton
var timelyButton;
(function () {
"use strict";
var context = window;
var mobile = {
Android: function () {
return navigator.userAgent.match(/Android/i) ? true : false;
},
BlackBerry: function () {
return navigator.userAgent.match(/BlackBerry/i) ? true : false;
},
iOS: function () {
return navigator.userAgent.match(/iPhone|iPod/i) ? true : false;
},
Windows: function () {
return navigator.userAgent.match(/IEMobile/i) ? true : false;
},
any: function () {
return (mobile.Android() || mobile.BlackBerry() || mobile.iOS() || mobile.Windows());
}
};
timelyButton = function (id, opts) {
var options = opts || {};
var businessId = id;
var resellerCode = options.reseller || resellerCode || '';
var productId = options.product || productId || '';
var categoryId = options.category || categoryId || '';
var staffId = options.staff || staffId || '';
var locationId = options.location || locationId || '';
var giftVoucherId = options.giftVoucherId || giftVoucherId || '';
var isPurchaseButton = options.isPurchaseButton != null ? options.isPurchaseButton : false; // default not a purchase
var dontCreateButton = !!options.dontCreateButton;
window.timelyBookFrame = {};
var XD;
var style = options.style || 'light';
var buttonId = options.buttonId || false;
var bookButton;
var scriptSource = (function() {
var script = document.getElementById('timelyScript');
if (script.getAttribute.length !== undefined) {
return script.src;
}
return script.getAttribute('src', -1);
}());
var isOwnImage = !!options.imgSrc;
var imgButtonType = isPurchaseButton ? "purchase-buttons" : "book-buttons";
var imgSrc = options.imgSrc || getDomain() + '/images/' + imgButtonType + '/button_' + style + '#2x.png';
var hoverSrc = getDomain() + '/images/' + imgButtonType + '/button_' + style + '_hover#2x.png';
var activeSrc = getDomain() + '/images/' + imgButtonType + '/button_' + style + '_active#2x.png';
var locationUrl = (isPurchaseButton ? '/giftvoucher/details/' : '/booking/location/') + businessId;
function init() {
if (dontCreateButton) return true;
if (isOwnImage) {
bookButton = document.createElement('a');
bookButton.href = 'javascript:void(0)';
bookButton.onclick = eventHandler.prototype.Book;
bookButton.innerHTML = '<img src=\'' + imgSrc + '\' border=\'0\' />';
} else {
bookButton = document.createElement('a');
bookButton.style.backgroundImage = "url(" + imgSrc + ")";
bookButton.style.backgroundRepeat = "no-repeat";
bookButton.style.backgroundPosition = "0px 0px";
bookButton.style.backgroundSize = (isPurchaseButton ? "220px" : "162px") + " 40px";
bookButton.style.width = isPurchaseButton ? "220px" : "162px";
bookButton.style.height = "40px";
bookButton.style.display = "inline-block";
bookButton.href = 'javascript:void(0)';
bookButton.onclick = eventHandler.prototype.Book;
bookButton.innerHTML += '<img src="' + hoverSrc + '" style="display:none;" border=\'0\' />';
bookButton.innerHTML += '<img src="' + activeSrc + '" style="display:none;" border=\'0\' />';
bookButton.onmouseenter = function() { this.style.backgroundImage = "url(" + hoverSrc + ")"; };
bookButton.onmouseout = function () { this.style.backgroundImage = "url(" + imgSrc + ")"; };
bookButton.onmousedown = function () { this.style.backgroundImage = "url(" + activeSrc + ")"; };
bookButton.onmouseup = function () { this.style.backgroundImage = "url(" + hoverSrc + ")"; };
}
var insertionPoint = findInsertionPoint(buttonId);
insertAfter(bookButton, insertionPoint);
}
function findInsertionPoint(buttonId) {
var insertionPoint = false;
if (buttonId) {
insertionPoint = document.getElementById(buttonId);
} else {
if (("currentScript" in document)) {
insertionPoint = document.currentScript;
} else {
var scripts = document.getElementsByTagName('script');
insertionPoint = scripts[scripts.length - 1];
}
}
return insertionPoint;
}
function getDomain() {
return ('https:' == document.location.protocol ? 'https://' : 'http://') + scriptSource.match( /:\/\/(.[^/]+)/ )[1];
}
function startBooking() {
var url = "";
if (resellerCode) {
url += '&reseller=' + resellerCode;
}
if (productId) {
url += '&productId=' + productId;
}
if (categoryId) {
url += '&categoryId=' + categoryId;
}
if (staffId) {
url += '&staffId=' + staffId;
}
if (locationId) {
url += '&locationId=' + locationId;
}
if (giftVoucherId) {
url += '&giftVoucherId=' + giftVoucherId;
}
if (window.innerWidth < 768 || mobile.any()) {
url = getDomain() + locationUrl + "?mobile=true" + url;
window.location.href = url;
return;
}
window.timelyBookFrame = document.createElement('iframe');
window.timelyBookFrame.className = 'timely-book-frame';
window.timelyBookFrame.style.cssText = 'width: 100%; height: 100%; position: fixed; top: 0; left: 0; z-index: 99999999;';
window.timelyBookFrame.setAttribute('frameBorder', 0);
window.timelyBookFrame.setAttribute('allowTransparency', 'true');
url = getDomain() + (isPurchaseButton ? '/giftvoucher' : '/booking') + '/overlay/' + businessId + '?x' + url;
url += '#' + encodeURIComponent(document.location.href);
window.timelyBookFrame.src = url;
window.timelyBookFrame.style.display = 'none';
document.getElementsByTagName('body')[0].appendChild(window.timelyBookFrame);
var element = document.getElementById('timely-lightbox');
if (typeof(element) != 'undefined' && element != null) {
$('#timely-lightbox').fadeOut();
}
}
function insertAfter(f, n) {
var p = n.parentNode;
if (n.nextSibling) {
p.insertBefore(f, n.nextSibling);
} else {
p.appendChild(f);
}
}
function eventHandler() {
// prototype instance
}
eventHandler.prototype.Book = function() {
startBooking();
};
// everything is wrapped in the XD function to reduce namespace collisions
XD = function () {
var interval_id,
last_hash,
cache_bust = 1,
attached_callback,
window = context;
return {
postMessage: function (message, target_url, target) {
if (!target_url) {
return;
}
target = target || parent; // default to parent
if (window['postMessage']) {
// the browser supports window.postMessage, so call it with a targetOrigin
// set appropriately, based on the target_url parameter.
target['postMessage'](message, target_url.replace(/([^:]+:\/\/[^\/]+).*/, '$1'));
} else if (target_url) {
// the browser does not support window.postMessage, so use the window.location.hash fragment hack
target.location = target_url.replace(/#.*$/, '') + '#' + (+new Date) + (cache_bust++) + '&' + message;
}
},
receiveMessage: function (callback, source_origin) {
// browser supports window.postMessage
if (window['postMessage']) {
// bind the callback to the actual event associated with window.postMessage
if (callback) {
attached_callback = function (e) {
if ((typeof source_origin === 'string' && e.origin !== source_origin)
|| (Object.prototype.toString.call(source_origin) === "[object Function]" && source_origin(e.origin) === !1)) {
return !1;
}
callback(e);
};
}
if (window['addEventListener']) {
window[callback ? 'addEventListener' : 'removeEventListener']('message', attached_callback, !1);
} else {
window[callback ? 'attachEvent' : 'detachEvent']('onmessage', attached_callback);
}
} else {
// a polling loop is started & callback is called whenever the location.hash changes
interval_id && clearInterval(interval_id);
interval_id = null;
if (callback) {
interval_id = setInterval(function () {
var hash = document.location.hash,
re = /^#?\d+&/;
if (hash !== last_hash && re.test(hash)) {
last_hash = hash;
callback({ data: hash.replace(re, '') });
}
}, 100);
}
}
}
};
}();
// setup a callback to handle the dispatched MessageEvent. if window.postMessage is supported the passed
// event will have .data, .origin and .source properties. otherwise, it will only have the .data property.
XD.receiveMessage(function (message) {
if (message.data == 'close') {
var element = document.getElementById('timely-lightbox');
if (typeof (element) != 'undefined' && element != null) {
$('#timely-lightbox').show();
}
if (window.timelyBookFrame && window.timelyBookFrame.parentNode) window.timelyBookFrame.parentNode.removeChild(window.timelyBookFrame);
}
if (message.data == 'open' && window.timelyBookFrame) {
window.timelyBookFrame.style.display = 'block';
}
}, getDomain());
init();
// expose the BookButton API
return {
start: function() {
startBooking();
}
};
};
})();
So how can I run this javascript when I click the button?
Any help would be greatly appreciated!
You could create a script tag automatically if the button has been clicked.
document.getElementById('myButton').addEventListener('click', () => {
const script = document.createElement("script");
script.src = 'my-other-file.js';
document.head.appendChild(script);
})
<button id="myButton">Load JS File</button>
Is there any plugin similar to the iPad-like password field behaviour. We need to show only the focus number that the customer enters when they enter their credit card number, and then switch to a bullet once the customer types the next number.
For numbers that have been entered prior to the number being entered, they all need to be changed to the bullet style.
Not sure about Jquery plugin. tried this out. Hope this works for you - http://jsfiddle.net/Lhw7xcy6/12/
(function () {
var config = {},
bulletsInProgress = false,
bulletTimeout = null,
defaultOpts = {
className: 'input-long',
maxLength: '16',
type: 'tel',
autoComplete: 'off'
};
var generateBullets = function (n) {
var bullets = '';
for (var i = 0; i < n; i++) {
bullets += "\u25CF";
}
return bullets;
},
getCursorPosition = function (elem) {
var el = $(elem).get(0);
var pos = 0;
var posEnd = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
posEnd = el.selectionEnd;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
posEnd = Sel.text.length;
}
return [pos, posEnd];
},
keyInputHandler = function (e, elem, $inpField) {
var keyCode = e.which || e.keyCode,
timeOut = 0,
$bulletField = $(elem),
tempInp = $bulletField.data('tempInp'),
numBullets = $bulletField.data('numBullets');
var position = getCursorPosition(elem);
if (keyCode >= 48 && keyCode <= 57) {
e.preventDefault();
clearTimeout(bulletTimeout);
$bulletField.val(generateBullets(numBullets) + String.fromCharCode(keyCode));
tempInp += String.fromCharCode(keyCode);
numBullets += 1;
bulletsInProgress = true;
timeOut = 3000;
} else if (keyCode == 8) {
clearTimeout(bulletTimeout);
tempInp = (position[0] == position[1]) ? tempInp.substring(0, position[0] - 1) + tempInp.substring(position[1]) : tempInp.substring(0, position[0]) + tempInp.substring(position[1]);
numBullets = (position[0] == position[1]) ? numBullets - 1 : numBullets - (position[1] - position[0]);
tempInp = ($.trim($bulletField.val()) === '') ? '' : tempInp;
numBullets = ($.trim($bulletField.val()) === '') ? 0 : numBullets;
timeOut = 0;
} else {
e.preventDefault();
return false;
}
$bulletField.data('numBullets', numBullets);
$bulletField.data('tempInp', tempInp);
$inpField.val(tempInp);
$('#output').val(tempInp); // testing purpose
bulletTimeout = setTimeout(function () {
$bulletField.val(generateBullets(numBullets));
bulletsInProgress = false;
}, timeOut);
};
$.fn.bulletField = function (options) {
var opts = $.extend({}, defaultOpts, options);
//console.log(opts);
this.each(function () {
var $inpField = $(this),
id = $inpField.attr('id');
$inpField.after('<input id="bullet_' + id + '" type=' + opts.type + ' maxlength=' + opts.maxLength + ' autocomplete=' + opts.autoComplete + ' class=' + opts.className + '>');
$inpField.hide();
var bulletFieldId = 'bullet_' + id;
var $bulletField = $('#' + bulletFieldId);
$bulletField.data('numBullets', 0);
$bulletField.data('tempInp', '');
$('#' + bulletFieldId).on('keydown', function (e) {
keyInputHandler(e, this, $inpField);
});
$('#' + bulletFieldId).on('blur', function () {
//$inpField.trigger('blur');
});
});
return this;
};
}());
$(function () {
/*USAGE - invoke the plugin appropriately whenever needed. example -onclick,onfocus,mousedown etc.*/
//$('body').on('mousedown', '#bulletField', function () {
$('#bulletField').bulletField();
//$('body').off('mousedown');
// });
/* ---OR ----
$('#bulletField').bulletField({
className: 'input-short',
maxLength : '4'
});*/
});
I have this code below i am trying to get the id from within the click function but this.id does now work from within the click function i think because the code does not run until clicked does anyone know a way to get the id at the time the each loop runs?
$(html).each(function() {
if($( this ).filter('.target').html()){
window["button"+this.id] = {
text: "Edit "+$($(html).filter('#'+this.id).html()).filter('#A1').text(),
click: function() {
$('#2').html($($(html).filter('#'+this.id).html()).filter('#B2').text());
var start = $($( html ).filter('#'+this.id).html()).filter('#A1').text();
$("#start").val(start);
var finish = $($(html).filter('#'+this.id).html()).filter('#A2').text();
$("#finish").val(finish);
var breaktime = $($(html).filter('#'+this.id).html()).filter('#A3').text();
$("#break").val(breaktime);
var grade = $($(html).filter('#'+this.id).html()).filter('#A4').text();
$("#grade").val(grade);
var PM = $($(html).filter('#'+this.id).html()).filter('#A9').text();
if(PM == '1') { $('#PM').prop('checked', true); }else{ $('#PM').prop('checked', false); }
var NS = $($(html).filter('#'+this.id).html()).filter('#NS').text();
if(NS == '1') { $('#NS').prop('checked', true); }else{ $('#NS').prop('checked', false); }
var RDO = $($(html).filter('#'+this.id).html()).filter('#A12').text();
if(RDO == '1') { $('#RDO').prop('checked', true); }else{ $('#RDO').prop('checked', false); }
var OrdHours = $($(html).filter('#'+this.id).html()).filter('#A5').text();
$("#ordhrs").val(OrdHours);
var x150 = $($(html).filter('#'+this.id).html()).filter('#A11').text();
$("#OTx150").val(x150);
var departmentID = $($(html).filter('#'+this.id).html()).filter('#A6').text();
$("select#ChangeDeparment").val(departmentID);
total = $($(html).filter('#'+this.id).html()).filter('#A8').html();
totalhrs = $($(html).filter('#'+this.id).html()).filter('#A7').html();
$("#total").html(totalhrs +"<br />" +total);
adjustmentID = $($(html).filter('#'+this.id).html()).filter('#B1').text();
no_adjustment = false;
$( this ).dialog( "close" );
}
}
newArray.push(window["button"+this.id]);
}
});
Define this as a variable to keep your scope
var self = this;
full example below
$(html).each(function() {
var self = this;
if ($(self).filter('.target').html()) {
window["button" + self.id] = {
text: "Edit " + $($(html).filter('#' + self.id).html()).filter('#A1').text(),
click: function() {
$('#2').html($($(html).filter('#' + self.id).html()).filter('#B2').text());
var start = $($(html).filter('#' + self.id).html()).filter('#A1').text();
$("#start").val(start);
var finish = $($(html).filter('#' + self.id).html()).filter('#A2').text();
$("#finish").val(finish);
var breaktime = $($(html).filter('#' + self.id).html()).filter('#A3').text();
$("#break").val(breaktime);
var grade = $($(html).filter('#' + self.id).html()).filter('#A4').text();
$("#grade").val(grade);
var PM = $($(html).filter('#' + self.id).html()).filter('#A9').text();
if (PM == '1') {
$('#PM').prop('checked', true);
} else {
$('#PM').prop('checked', false);
}
var NS = $($(html).filter('#' + self.id).html()).filter('#NS').text();
if (NS == '1') {
$('#NS').prop('checked', true);
} else {
$('#NS').prop('checked', false);
}
var RDO = $($(html).filter('#' + self.id).html()).filter('#A12').text();
if (RDO == '1') {
$('#RDO').prop('checked', true);
} else {
$('#RDO').prop('checked', false);
}
var OrdHours = $($(html).filter('#' + self.id).html()).filter('#A5').text();
$("#ordhrs").val(OrdHours);
var x150 = $($(html).filter('#' + self.id).html()).filter('#A11').text();
$("#OTx150").val(x150);
var departmentID = $($(html).filter('#' + self.id).html()).filter('#A6').text();
$("select#ChangeDeparment").val(departmentID);
total = $($(html).filter('#' + self.id).html()).filter('#A8').html();
totalhrs = $($(html).filter('#' + self.id).html()).filter('#A7').html();
$("#total").html(totalhrs + "<br />" + total);
adjustmentID = $($(html).filter('#' + self.id).html()).filter('#B1').text();
no_adjustment = false;
$(self).dialog("close");
}
}
newArray.push(window["button" + self.id]);
}
});