light weight javascript text editor not working - javascript

I have this light weight text editor that go on a webpage. It all displays well and work almost as expected but when you post the form the text area values do not get posted, I suspect the text is not inserted into the 'real' text box from the 'fake' textbox...
Here is the javascript and css and html. You will have to run this locally to output in php or something the $_POST values, to see what I mean.
window.FontAwesomeKitConfig = {"asyncLoading":{"enabled":true},"autoA11y":{"enabled":true},"baseUrl":"https://ka-f.fontawesome.com","baseUrlKit":"https://kit.fontawesome.com","detectConflictsUntil":null,"iconUploads":{},"id":44475219,"license":"free","method":"css","minify":{"enabled":true},"token":"7ce56be44b","v4FontFaceShim":{"enabled":false},"v4shim":{"enabled":false},"version":"5.15.4"};
!function(t){"function"==typeof define&&define.amd?define("kit-loader",t):t()}((function(){"use strict";function t(e){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(e)}function e(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function n(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function r(t){for(var r=1;r<arguments.length;r++){var o=null!=arguments[r]?arguments[r]:{};r%2?n(Object(o),!0).forEach((function(n){e(t,n,o[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(o)):n(Object(o)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(o,e))}))}return t}function o(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(t)))return;var n=[],r=!0,o=!1,i=void 0;try{for(var c,a=t[Symbol.iterator]();!(r=(c=a.next()).done)&&(n.push(c.value),!e||n.length!==e);r=!0);}catch(t){o=!0,i=t}finally{try{r||null==a.return||a.return()}finally{if(o)throw i}}return n}(t,e)||function(t,e){if(!t)return;if("string"==typeof t)return i(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return i(t,e)}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function c(t,e){var n=e&&e.addOn||"",r=e&&e.baseFilename||t.license+n,o=e&&e.minify?".min":"",i=e&&e.fileSuffix||t.method,c=e&&e.subdir||t.method;return t.baseUrl+"/releases/"+("latest"===t.version?"latest":"v".concat(t.version))+"/"+c+"/"+r+o+"."+i}function a(t){return t.baseUrlKit+"/"+t.token+"/"+t.id+"/kit-upload.css"}function u(t,e){var n=e||["fa"],r="."+Array.prototype.join.call(n,",."),o=t.querySelectorAll(r);Array.prototype.forEach.call(o,(function(e){var n=e.getAttribute("title");e.setAttribute("aria-hidden","true");var r=!e.nextElementSibling||!e.nextElementSibling.classList.contains("sr-only");if(n&&r){var o=t.createElement("span");o.innerHTML=n,o.classList.add("sr-only"),e.parentNode.insertBefore(o,e.nextSibling)}}))}var f,s=function(){},d="undefined"!=typeof global&&void 0!==global.process&&"function"==typeof global.process.emit,l="undefined"==typeof setImmediate?setTimeout:setImmediate,h=[];function m(){for(var t=0;t<h.length;t++)h[t][0](h[t][1]);h=[],f=!1}function p(t,e){h.push([t,e]),f||(f=!0,l(m,0))}function y(t){var e=t.owner,n=e._state,r=e._data,o=t[n],i=t.then;if("function"==typeof o){n="fulfilled";try{r=o(r)}catch(t){w(i,t)}}b(i,r)||("fulfilled"===n&&v(i,r),"rejected"===n&&w(i,r))}function b(e,n){var r;try{if(e===n)throw new TypeError("A promises callback cannot return that same promise.");if(n&&("function"==typeof n||"object"===t(n))){var o=n.then;if("function"==typeof o)return o.call(n,(function(t){r||(r=!0,n===t?g(e,t):v(e,t))}),(function(t){r||(r=!0,w(e,t))})),!0}}catch(t){return r||w(e,t),!0}return!1}function v(t,e){t!==e&&b(t,e)||g(t,e)}function g(t,e){"pending"===t._state&&(t._state="settled",t._data=e,p(S,t))}function w(t,e){"pending"===t._state&&(t._state="settled",t._data=e,p(O,t))}function A(t){t._then=t._then.forEach(y)}function S(t){t._state="fulfilled",A(t)}function O(t){t._state="rejected",A(t),!t._handled&&d&&global.process.emit("unhandledRejection",t._data,t)}function j(t){global.process.emit("rejectionHandled",t)}function E(t){if("function"!=typeof t)throw new TypeError("Promise resolver "+t+" is not a function");if(this instanceof E==!1)throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._then=[],function(t,e){function n(t){w(e,t)}try{t((function(t){v(e,t)}),n)}catch(t){n(t)}}(t,this)}E.prototype={constructor:E,_state:"pending",_then:null,_data:void 0,_handled:!1,then:function(t,e){var n={owner:this,then:new this.constructor(s),fulfilled:t,rejected:e};return!e&&!t||this._handled||(this._handled=!0,"rejected"===this._state&&d&&p(j,this)),"fulfilled"===this._state||"rejected"===this._state?p(y,n):this._then.push(n),n.then},catch:function(t){return this.then(null,t)}},E.all=function(t){if(!Array.isArray(t))throw new TypeError("You must pass an array to Promise.all().");return new E((function(e,n){var r=[],o=0;function i(t){return o++,function(n){r[t]=n,--o||e(r)}}for(var c,a=0;a<t.length;a++)(c=t[a])&&"function"==typeof c.then?c.then(i(a),n):r[a]=c;o||e(r)}))},E.race=function(t){if(!Array.isArray(t))throw new TypeError("You must pass an array to Promise.race().");return new E((function(e,n){for(var r,o=0;o<t.length;o++)(r=t[o])&&"function"==typeof r.then?r.then(e,n):e(r)}))},E.resolve=function(e){return e&&"object"===t(e)&&e.constructor===E?e:new E((function(t){t(e)}))},E.reject=function(t){return new E((function(e,n){n(t)}))};var _="function"==typeof Promise?Promise:E;function P(t,e){var n=e.fetch,r=e.XMLHttpRequest,o=e.token,i=t;return"URLSearchParams"in window?(i=new URL(t)).searchParams.set("token",o):i=i+"?token="+encodeURIComponent(o),i=i.toString(),new _((function(t,e){if("function"==typeof n)n(i,{mode:"cors",cache:"default"}).then((function(t){if(t.ok)return t.text();throw new Error("")})).then((function(e){t(e)})).catch(e);else if("function"==typeof r){var o=new r;o.addEventListener("loadend",(function(){this.responseText?t(this.responseText):e(new Error(""))}));["abort","error","timeout"].map((function(t){o.addEventListener(t,(function(){e(new Error(""))}))})),o.open("GET",i),o.send()}else{e(new Error(""))}}))}function C(t,e,n){var r=t;return[[/(url\("?)\.\.\/\.\.\/\.\./g,function(t,n){return"".concat(n).concat(e)}],[/(url\("?)\.\.\/webfonts/g,function(t,r){return"".concat(r).concat(e,"/releases/v").concat(n,"/webfonts")}],[/(url\("?)https:\/\/kit-free([^.])*\.fontawesome\.com/g,function(t,n){return"".concat(n).concat(e)}]].forEach((function(t){var e=o(t,2),n=e[0],i=e[1];r=r.replace(n,i)})),r}function F(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){},o=e.document||o,i=u.bind(u,o,["fa","fab","fas","far","fal","fad","fak"]),f=Object.keys(t.iconUploads||{}).length>0;t.autoA11y.enabled&&n(i);var s=[{id:"fa-main",addOn:void 0}];t.v4shim.enabled&&s.push({id:"fa-v4-shims",addOn:"-v4-shims"}),t.v4FontFaceShim.enabled&&s.push({id:"fa-v4-font-face",addOn:"-v4-font-face"}),f&&s.push({id:"fa-kit-upload",customCss:!0});var d=s.map((function(n){return new _((function(o,i){P(n.customCss?a(t):c(t,{addOn:n.addOn,minify:t.minify.enabled}),e).then((function(i){o(U(i,r(r({},e),{},{baseUrl:t.baseUrl,version:t.version,id:n.id,contentFilter:function(t,e){return C(t,e.baseUrl,e.version)}})))})).catch(i)}))}));return _.all(d)}function U(t,e){var n=e.contentFilter||function(t,e){return t},r=document.createElement("style"),o=document.createTextNode(n(t,e));return r.appendChild(o),r.media="all",e.id&&r.setAttribute("id",e.id),e&&e.detectingConflicts&&e.detectionIgnoreAttr&&r.setAttributeNode(document.createAttribute(e.detectionIgnoreAttr)),r}function k(t,e){e.autoA11y=t.autoA11y.enabled,"pro"===t.license&&(e.autoFetchSvg=!0,e.fetchSvgFrom=t.baseUrl+"/releases/"+("latest"===t.version?"latest":"v".concat(t.version))+"/svgs",e.fetchUploadedSvgFrom=t.uploadsUrl);var n=[];return t.v4shim.enabled&&n.push(new _((function(n,o){P(c(t,{addOn:"-v4-shims",minify:t.minify.enabled}),e).then((function(t){n(I(t,r(r({},e),{},{id:"fa-v4-shims"})))})).catch(o)}))),n.push(new _((function(n,o){P(c(t,{minify:t.minify.enabled}),e).then((function(t){var o=I(t,r(r({},e),{},{id:"fa-main"}));n(function(t,e){var n=e&&void 0!==e.autoFetchSvg?e.autoFetchSvg:void 0,r=e&&void 0!==e.autoA11y?e.autoA11y:void 0;void 0!==r&&t.setAttribute("data-auto-a11y",r?"true":"false");n&&(t.setAttributeNode(document.createAttribute("data-auto-fetch-svg")),t.setAttribute("data-fetch-svg-from",e.fetchSvgFrom),t.setAttribute("data-fetch-uploaded-svg-from",e.fetchUploadedSvgFrom));return t}(o,e))})).catch(o)}))),_.all(n)}function I(t,e){var n=document.createElement("SCRIPT"),r=document.createTextNode(t);return n.appendChild(r),n.referrerPolicy="strict-origin",e.id&&n.setAttribute("id",e.id),e&&e.detectingConflicts&&e.detectionIgnoreAttr&&n.setAttributeNode(document.createAttribute(e.detectionIgnoreAttr)),n}function L(t){var e,n=[],r=document,o=r.documentElement.doScroll,i=(o?/^loaded|^c/:/^loaded|^i|^c/).test(r.readyState);i||r.addEventListener("DOMContentLoaded",e=function(){for(r.removeEventListener("DOMContentLoaded",e),i=1;e=n.shift();)e()}),i?setTimeout(t,0):n.push(t)}function T(t){"undefined"!=typeof MutationObserver&&new MutationObserver(t).observe(document,{childList:!0,subtree:!0})}try{if(window.FontAwesomeKitConfig){var x=window.FontAwesomeKitConfig,M={detectingConflicts:x.detectConflictsUntil&&new Date<=new Date(x.detectConflictsUntil),detectionIgnoreAttr:"data-fa-detection-ignore",fetch:window.fetch,token:x.token,XMLHttpRequest:window.XMLHttpRequest,document:document},D=document.currentScript,N=D?D.parentElement:document.head;(function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return"js"===t.method?k(t,e):"css"===t.method?F(t,e,(function(t){L(t),T(t)})):void 0})(x,M).then((function(t){t.map((function(t){try{N.insertBefore(t,D?D.nextSibling:null)}catch(e){N.appendChild(t)}})),M.detectingConflicts&&D&&L((function(){D.setAttributeNode(document.createAttribute(M.detectionIgnoreAttr));var t=function(t,e){var n=document.createElement("script");return e&&e.detectionIgnoreAttr&&n.setAttributeNode(document.createAttribute(e.detectionIgnoreAttr)),n.src=c(t,{baseFilename:"conflict-detection",fileSuffix:"js",subdir:"js",minify:t.minify.enabled}),n}(x,M);document.body.appendChild(t)}))})).catch((function(t){console.error("".concat("Font Awesome Kit:"," ").concat(t))}))}}catch(t){console.error("".concat("Font Awesome Kit:"," ").concat(t))}}));
//internal variables
var show = false;
//textAreaSelector
const textAreaSelector = document.getElementById('text-editor');
//buttonsToolbar
var buttonsToolbar = document.createElement('div');
buttonsToolbar.setAttribute('id', 'buttonsToolbar');
///buttonsToolbar
//textEditor
var textEditor = document.createElement('div');
textEditor.setAttribute('id', 'textEditor');
textEditor.setAttribute('contentEditable', 'true');
///textEditor
insidetext = document.getElementById('text-editor').textContent;
textEditor.innerHTML = insidetext;
//functions
function insertAfter(insertObject) {
insertObject.forEach(insertObj => {
insertObj.reference.parentNode.insertBefore(insertObj.new, insertObj.reference.nextSibling);
});
}
var buttons = [
{
name: 'alignLeft',
cmd: 'justifyLeft',
icon: 'fas fa-align-left'
},
{
name: 'alignCenter',
cmd: 'justifyCenter',
icon: 'fas fa-align-center'
},
{
name: 'alignJustify',
cmd: 'justifyFull',
icon: 'fas fa-align-justify'
},
{
name: 'alignRight',
cmd: 'justifyRight',
icon: 'fas fa-align-right'
},
{
name: 'bold',
cmd: 'bold',
icon: 'fas fa-bold'
},
{
name: 'italic',
cmd: 'italic',
icon: 'fas fa-italic'
},
{
name: 'underline',
cmd: 'underline',
icon: 'fas fa-underline'
},
{
name: 'insertOrderedList',
cmd: 'insertOrderedList',
icon: 'fas fa-list-ol'
},
{
name: 'insertUnorderedList',
cmd: 'insertUnorderedList',
icon: 'fas fa-list-ul'
},
// {
// name: 'insertImage',
// cmd: 'insertImage',
// icon: 'fas fa-image'
// },
// {
// name: 'insertLink',
// cmd: 'createLink',
// icon: 'fas fa-link'
// },
{
name: 'showCode',
cmd: 'showCode',
icon: 'fas fa-code'
},
]
buttons.forEach(button => {
//buttonElement
let buttonElement = document.createElement('button');
buttonElement.type = 'button';
buttonElement.setAttribute('id', button.name);
///buttonElement
//buttonIcon
let buttonIcon = document.createElement('i');
buttonIcon.setAttribute('class', button.icon);
///buttonIcon
buttonElement.addEventListener('click', () => {
let current = document.getElementsByClassName('active');
if (current.length > 0) {
current[0].classList.remove('active');
}
buttonElement.classList.add('active');
switch (button.cmd) {
case 'insertImage':
url = prompt('Enter image link here: ', '');
if (url) {
document.execCommand(button.cmd, false, url);
}
const images = textEditor.querySelectorAll('img');
images.forEach(img => {
img.style.maxWidth = '500px';
});
break;
// case 'createLink':
// url = prompt('Enter URL link here: ', '');
// text = prompt('Enter link text here: ', '');
// if (url && text) {
// document.execCommand(
// 'insertHTML',
// false,
// `<a href=${url} target='_blank'>${text}</a>`
// );
// }
const links = textEditor.querySelectorAll('a');
links.forEach(lnk => {
lnk.target = '_blank';
lnk.addEventListener('mouseover', () => {
textEditor.setAttribute('contentEditable', 'false');
});
lnk.addEventListener('mouseout', () => {
textEditor.setAttribute('contentEditable', 'true');
});
});
break;
case 'showCode':
if (show) {
buttonElement.classList.remove('active');
textEditor.innerHTML = textEditor.textContent;
show = false;
} else {
textEditor.textContent = textEditor.innerHTML;
show = true;
}
break;
default:
document.execCommand(button.cmd, false, null);
break;
}
});
buttonElement.appendChild(buttonIcon);
buttonsToolbar.appendChild(buttonElement);
});
insertAfter([
{
reference: textAreaSelector,
new: textEditor
},
{
reference: textAreaSelector,
new: buttonsToolbar
}
]);
textAreaSelector.remove();
#buttonsToolbar button:last-child {
margin: 0;
}
#buttonsToolbar button {
width: 30px;
height: 30px;
margin: 0 5px 0 0;
border: none;
outline: none;
cursor: pointer;
}
#buttonsToolbar {
width: fit-content;
}
#textEditor {
width: 100%;
height: 250px;
margin-top: 5px;
padding: 5px;
color: black;
border: 1px solid rgba(0, 0, 0, .1);
border-radius: 3px;
outline: none;
background-color: white;
box-shadow: 0 8px 18px rgba(0, 0, 0, .1);
}
#buttonsToolbar button.active {
background-color: rgb(214, 214, 214)
}
#textEditor p {
color:black;
}
<form method="post" accept-charset="utf-8">
<div class="input textarea">
<label for="address">Address (200 characters)</label>
<textarea name="businessaddress" id="text-editor" rows="2"></textarea>
</div>
<button class="btn btn-primary float-end" type="submit">Submit</button>
</form>

Some points you were missing:
You need the <textarea> element since an editable div is not a proper form element (so you won't get any $_POST data).
Therefore you need to delete
textAreaSelector.remove(); – but you can just hide it via e.g a display:none;
Besides, you will also need to synchronize current text inputs between editor div and textarea:
textEditor.addEventListener('keyup', function(e){
let currentContent = e.currentTarget.innerHTML;
textAreaSelector.value = currentContent;
})
Edit: editor updating on button click
//internal variables
var show = false;
//textAreaSelector
const textAreaSelector = document.getElementById("text-editor");
//buttonsToolbar
var buttonsToolbar = document.createElement("div");
buttonsToolbar.setAttribute("id", "buttonsToolbar");
var textEditor = document.createElement("div");
textEditor.setAttribute("id", "textEditor");
textEditor.setAttribute("contentEditable", "true");
insidetext = textAreaSelector.textContent;
textEditor.innerHTML = insidetext;
textEditor.addEventListener('keyup', function(e) {
updateText()
});
// update/synchronize and sanitize text
function updateText() {
setTimeout(function() {
let currentContent = textEditor.innerHTML;
let currentContentTxt = textEditor.textContent.replaceAll(/\s/g, '');
currentContent = currentContent.replaceAll('<div>', '<p>').
replaceAll('</div>', '</p>').
replaceAll('<i>', '<em>').
replaceAll('</i>', '</em>').
replaceAll('<b>', '<strong>').
replaceAll('</b>', '</strong>').
replaceAll('<div style=', '<p style=').
replaceAll('</div>', '</p>');
// remove empty html elements
if (!currentContentTxt) {
currentContent = '';
}
textAreaSelector.value = currentContent;
//console.log(currentContent);
//console.log(currentContentTxt);
}, 200);
}
//functions
function insertAfter(insertObject) {
insertObject.forEach((insertObj) => {
insertObj.reference.parentNode.insertBefore(
insertObj.new,
insertObj.reference.nextSibling
);
});
}
var buttons = [{
name: "alignLeft",
cmd: "justifyLeft",
icon: "fas fa-align-left"
},
{
name: "alignCenter",
cmd: "justifyCenter",
icon: "fas fa-align-center"
},
{
name: "alignJustify",
cmd: "justifyFull",
icon: "fas fa-align-justify"
},
{
name: "alignRight",
cmd: "justifyRight",
icon: "fas fa-align-right"
},
{
name: "bold",
cmd: "bold",
icon: "fas fa-bold"
},
{
name: "italic",
cmd: "italic",
icon: "fas fa-italic"
},
{
name: "underline",
cmd: "underline",
icon: "fas fa-underline"
},
{
name: "insertOrderedList",
cmd: "insertOrderedList",
icon: "fas fa-list-ol"
},
{
name: "insertUnorderedList",
cmd: "insertUnorderedList",
icon: "fas fa-list-ul"
},
// {
// name: 'insertImage',
// cmd: 'insertImage',
// icon: 'fas fa-image'
// },
// {
// name: 'insertLink',
// cmd: 'createLink',
// icon: 'fas fa-link'
// },
{
name: "showCode",
cmd: "showCode",
icon: "fas fa-code"
}
];
buttons.forEach((button) => {
//buttonElement
let buttonElement = document.createElement("button");
buttonElement.type = "button";
buttonElement.setAttribute("id", button.name);
///buttonElement
//buttonIcon
let buttonIcon = document.createElement("i");
buttonIcon.setAttribute("class", button.icon);
///buttonIcon
buttonElement.addEventListener("click", () => {
let current = document.getElementsByClassName("active");
if (current.length > 0) {
current[0].classList.remove("active");
}
buttonElement.classList.add("active");
updateText();
switch (button.cmd) {
case "insertImage":
url = prompt("Enter image link here: ", "");
if (url) {
document.execCommand(button.cmd, false, url);
}
const images = textEditor.querySelectorAll("img");
images.forEach((img) => {
img.style.maxWidth = "500px";
});
break;
// case 'createLink':
// url = prompt('Enter URL link here: ', '');
// text = prompt('Enter link text here: ', '');
// if (url && text) {
// document.execCommand(
// 'insertHTML',
// false,
// `<a href=${url} target='_blank'>${text}</a>`
// );
// }
const links = textEditor.querySelectorAll("a");
links.forEach((lnk) => {
lnk.target = "_blank";
lnk.addEventListener("mouseover", () => {
textEditor.setAttribute("contentEditable", "false");
});
lnk.addEventListener("mouseout", () => {
textEditor.setAttribute("contentEditable", "true");
});
});
break;
case "showCode":
if (show) {
buttonElement.classList.remove("active");
textEditor.innerHTML = textEditor.textContent;
show = false;
} else {
textEditor.textContent = textEditor.innerHTML;
show = true;
}
break;
default:
document.execCommand(button.cmd, false, null);
break;
}
});
buttonElement.appendChild(buttonIcon);
buttonsToolbar.appendChild(buttonElement);
});
insertAfter([{
reference: textAreaSelector,
new: textEditor
},
{
reference: textAreaSelector,
new: buttonsToolbar
}
]);
//textAreaSelector.remove();
window.FontAwesomeKitConfig = {
asyncLoading: {
enabled: true
},
autoA11y: {
enabled: true
},
baseUrl: "https://ka-f.fontawesome.com",
baseUrlKit: "https://kit.fontawesome.com",
detectConflictsUntil: null,
iconUploads: {},
id: 44475219,
license: "free",
method: "css",
minify: {
enabled: true
},
token: "7ce56be44b",
v4FontFaceShim: {
enabled: false
},
v4shim: {
enabled: false
},
version: "5.15.4"
};
!(function(t) {
"function" == typeof define && define.amd ? define("kit-loader", t) : t();
})(function() {
"use strict";
function t(e) {
return (t =
"function" == typeof Symbol && "symbol" == typeof Symbol.iterator ?
function(t) {
return typeof t;
} :
function(t) {
return t &&
"function" == typeof Symbol &&
t.constructor === Symbol &&
t !== Symbol.prototype ?
"symbol" :
typeof t;
})(e);
}
function e(t, e, n) {
return (
e in t ?
Object.defineProperty(t, e, {
value: n,
enumerable: !0,
configurable: !0,
writable: !0
}) :
(t[e] = n),
t
);
}
function n(t, e) {
var n = Object.keys(t);
if (Object.getOwnPropertySymbols) {
var r = Object.getOwnPropertySymbols(t);
e &&
(r = r.filter(function(e) {
return Object.getOwnPropertyDescriptor(t, e).enumerable;
})),
n.push.apply(n, r);
}
return n;
}
function r(t) {
for (var r = 1; r < arguments.length; r++) {
var o = null != arguments[r] ? arguments[r] : {};
r % 2 ?
n(Object(o), !0).forEach(function(n) {
e(t, n, o[n]);
}) :
Object.getOwnPropertyDescriptors ?
Object.defineProperties(t, Object.getOwnPropertyDescriptors(o)) :
n(Object(o)).forEach(function(e) {
Object.defineProperty(t, e, Object.getOwnPropertyDescriptor(o, e));
});
}
return t;
}
function o(t, e) {
return (
(function(t) {
if (Array.isArray(t)) return t;
})(t) ||
(function(t, e) {
if ("undefined" == typeof Symbol || !(Symbol.iterator in Object(t)))
return;
var n = [],
r = !0,
o = !1,
i = void 0;
try {
for (
var c, a = t[Symbol.iterator](); !(r = (c = a.next()).done) &&
(n.push(c.value), !e || n.length !== e); r = !0
);
} catch (t) {
(o = !0), (i = t);
} finally {
try {
r || null == a.return || a.return();
} finally {
if (o) throw i;
}
}
return n;
})(t, e) ||
(function(t, e) {
if (!t) return;
if ("string" == typeof t) return i(t, e);
var n = Object.prototype.toString.call(t).slice(8, -1);
"Object" === n && t.constructor && (n = t.constructor.name);
if ("Map" === n || "Set" === n) return Array.from(t);
if (
"Arguments" === n ||
/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)
)
return i(t, e);
})(t, e) ||
(function() {
throw new TypeError(
"Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."
);
})()
);
}
function i(t, e) {
(null == e || e > t.length) && (e = t.length);
for (var n = 0, r = new Array(e); n < e; n++) r[n] = t[n];
return r;
}
function c(t, e) {
var n = (e && e.addOn) || "",
r = (e && e.baseFilename) || t.license + n,
o = e && e.minify ? ".min" : "",
i = (e && e.fileSuffix) || t.method,
c = (e && e.subdir) || t.method;
return (
t.baseUrl +
"/releases/" +
("latest" === t.version ? "latest" : "v".concat(t.version)) +
"/" +
c +
"/" +
r +
o +
"." +
i
);
}
function a(t) {
return t.baseUrlKit + "/" + t.token + "/" + t.id + "/kit-upload.css";
}
function u(t, e) {
var n = e || ["fa"],
r = "." + Array.prototype.join.call(n, ",."),
o = t.querySelectorAll(r);
Array.prototype.forEach.call(o, function(e) {
var n = e.getAttribute("title");
e.setAttribute("aria-hidden", "true");
var r = !e.nextElementSibling ||
!e.nextElementSibling.classList.contains("sr-only");
if (n && r) {
var o = t.createElement("span");
(o.innerHTML = n),
o.classList.add("sr-only"),
e.parentNode.insertBefore(o, e.nextSibling);
}
});
}
var f,
s = function() {},
d =
"undefined" != typeof global &&
void 0 !== global.process &&
"function" == typeof global.process.emit,
l = "undefined" == typeof setImmediate ? setTimeout : setImmediate,
h = [];
function m() {
for (var t = 0; t < h.length; t++) h[t][0](h[t][1]);
(h = []), (f = !1);
}
function p(t, e) {
h.push([t, e]), f || ((f = !0), l(m, 0));
}
function y(t) {
var e = t.owner,
n = e._state,
r = e._data,
o = t[n],
i = t.then;
if ("function" == typeof o) {
n = "fulfilled";
try {
r = o(r);
} catch (t) {
w(i, t);
}
}
b(i, r) || ("fulfilled" === n && v(i, r), "rejected" === n && w(i, r));
}
function b(e, n) {
var r;
try {
if (e === n)
throw new TypeError(
"A promises callback cannot return that same promise."
);
if (n && ("function" == typeof n || "object" === t(n))) {
var o = n.then;
if ("function" == typeof o)
return (
o.call(
n,
function(t) {
r || ((r = !0), n === t ? g(e, t) : v(e, t));
},
function(t) {
r || ((r = !0), w(e, t));
}
), !0
);
}
} catch (t) {
return r || w(e, t), !0;
}
return !1;
}
function v(t, e) {
(t !== e && b(t, e)) || g(t, e);
}
function g(t, e) {
"pending" === t._state && ((t._state = "settled"), (t._data = e), p(S, t));
}
function w(t, e) {
"pending" === t._state && ((t._state = "settled"), (t._data = e), p(O, t));
}
function A(t) {
t._then = t._then.forEach(y);
}
function S(t) {
(t._state = "fulfilled"), A(t);
}
function O(t) {
(t._state = "rejected"),
A(t), !t._handled && d && global.process.emit("unhandledRejection", t._data, t);
}
function j(t) {
global.process.emit("rejectionHandled", t);
}
function E(t) {
if ("function" != typeof t)
throw new TypeError("Promise resolver " + t + " is not a function");
if (this instanceof E == !1)
throw new TypeError(
"Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."
);
(this._then = []),
(function(t, e) {
function n(t) {
w(e, t);
}
try {
t(function(t) {
v(e, t);
}, n);
} catch (t) {
n(t);
}
})(t, this);
}
(E.prototype = {
constructor: E,
_state: "pending",
_then: null,
_data: void 0,
_handled: !1,
then: function(t, e) {
var n = {
owner: this,
then: new this.constructor(s),
fulfilled: t,
rejected: e
};
return (
(!e && !t) ||
this._handled ||
((this._handled = !0), "rejected" === this._state && d && p(j, this)),
"fulfilled" === this._state || "rejected" === this._state ?
p(y, n) :
this._then.push(n),
n.then
);
},
catch: function(t) {
return this.then(null, t);
}
}),
(E.all = function(t) {
if (!Array.isArray(t))
throw new TypeError("You must pass an array to Promise.all().");
return new E(function(e, n) {
var r = [],
o = 0;
function i(t) {
return (
o++,
function(n) {
(r[t] = n), --o || e(r);
}
);
}
for (var c, a = 0; a < t.length; a++)
(c = t[a]) && "function" == typeof c.then ?
c.then(i(a), n) :
(r[a] = c);
o || e(r);
});
}),
(E.race = function(t) {
if (!Array.isArray(t))
throw new TypeError("You must pass an array to Promise.race().");
return new E(function(e, n) {
for (var r, o = 0; o < t.length; o++)
(r = t[o]) && "function" == typeof r.then ? r.then(e, n) : e(r);
});
}),
(E.resolve = function(e) {
return e && "object" === t(e) && e.constructor === E ?
e :
new E(function(t) {
t(e);
});
}),
(E.reject = function(t) {
return new E(function(e, n) {
n(t);
});
});
var _ = "function" == typeof Promise ? Promise : E;
function P(t, e) {
var n = e.fetch,
r = e.XMLHttpRequest,
o = e.token,
i = t;
return (
"URLSearchParams" in window ?
(i = new URL(t)).searchParams.set("token", o) :
(i = i + "?token=" + encodeURIComponent(o)),
(i = i.toString()),
new _(function(t, e) {
if ("function" == typeof n)
n(i, {
mode: "cors",
cache: "default"
})
.then(function(t) {
if (t.ok) return t.text();
throw new Error("");
})
.then(function(e) {
t(e);
})
.catch(e);
else if ("function" == typeof r) {
var o = new r();
o.addEventListener("loadend", function() {
this.responseText ? t(this.responseText) : e(new Error(""));
});
["abort", "error", "timeout"].map(function(t) {
o.addEventListener(t, function() {
e(new Error(""));
});
}),
o.open("GET", i),
o.send();
} else {
e(new Error(""));
}
})
);
}
function C(t, e, n) {
var r = t;
return (
[
[
/(url\("?)\.\.\/\.\.\/\.\./g,
function(t, n) {
return "".concat(n).concat(e);
}
],
[
/(url\("?)\.\.\/webfonts/g,
function(t, r) {
return "".concat(r).concat(e, "/releases/v").concat(n, "/webfonts");
}
],
[
/(url\("?)https:\/\/kit-free([^.])*\.fontawesome\.com/g,
function(t, n) {
return "".concat(n).concat(e);
}
]
].forEach(function(t) {
var e = o(t, 2),
n = e[0],
i = e[1];
r = r.replace(n, i);
}),
r
);
}
function F(t, e) {
var n =
arguments.length > 2 && void 0 !== arguments[2] ?
arguments[2] :
function() {},
o = e.document || o,
i = u.bind(u, o, ["fa", "fab", "fas", "far", "fal", "fad", "fak"]),
f = Object.keys(t.iconUploads || {}).length > 0;
t.autoA11y.enabled && n(i);
var s = [{
id: "fa-main",
addOn: void 0
}];
t.v4shim.enabled && s.push({
id: "fa-v4-shims",
addOn: "-v4-shims"
}),
t.v4FontFaceShim.enabled &&
s.push({
id: "fa-v4-font-face",
addOn: "-v4-font-face"
}),
f && s.push({
id: "fa-kit-upload",
customCss: !0
});
var d = s.map(function(n) {
return new _(function(o, i) {
P(
n.customCss ?
a(t) :
c(t, {
addOn: n.addOn,
minify: t.minify.enabled
}),
e
)
.then(function(i) {
o(
U(
i,
r(
r({}, e), {}, {
baseUrl: t.baseUrl,
version: t.version,
id: n.id,
contentFilter: function(t, e) {
return C(t, e.baseUrl, e.version);
}
}
)
)
);
})
.catch(i);
});
});
return _.all(d);
}
function U(t, e) {
var n =
e.contentFilter ||
function(t, e) {
return t;
},
r = document.createElement("style"),
o = document.createTextNode(n(t, e));
return (
r.appendChild(o),
(r.media = "all"),
e.id && r.setAttribute("id", e.id),
e &&
e.detectingConflicts &&
e.detectionIgnoreAttr &&
r.setAttributeNode(document.createAttribute(e.detectionIgnoreAttr)),
r
);
}
function k(t, e) {
(e.autoA11y = t.autoA11y.enabled),
"pro" === t.license &&
((e.autoFetchSvg = !0),
(e.fetchSvgFrom =
t.baseUrl +
"/releases/" +
("latest" === t.version ? "latest" : "v".concat(t.version)) +
"/svgs"),
(e.fetchUploadedSvgFrom = t.uploadsUrl));
var n = [];
return (
t.v4shim.enabled &&
n.push(
new _(function(n, o) {
P(c(t, {
addOn: "-v4-shims",
minify: t.minify.enabled
}), e)
.then(function(t) {
n(I(t, r(r({}, e), {}, {
id: "fa-v4-shims"
})));
})
.catch(o);
})
),
n.push(
new _(function(n, o) {
P(c(t, {
minify: t.minify.enabled
}), e)
.then(function(t) {
var o = I(t, r(r({}, e), {}, {
id: "fa-main"
}));
n(
(function(t, e) {
var n =
e && void 0 !== e.autoFetchSvg ? e.autoFetchSvg : void 0,
r = e && void 0 !== e.autoA11y ? e.autoA11y : void 0;
void 0 !== r &&
t.setAttribute("data-auto-a11y", r ? "true" : "false");
n &&
(t.setAttributeNode(
document.createAttribute("data-auto-fetch-svg")
),
t.setAttribute("data-fetch-svg-from", e.fetchSvgFrom),
t.setAttribute(
"data-fetch-uploaded-svg-from",
e.fetchUploadedSvgFrom
));
return t;
})(o, e)
);
})
.catch(o);
})
),
_.all(n)
);
}
function I(t, e) {
var n = document.createElement("SCRIPT"),
r = document.createTextNode(t);
return (
n.appendChild(r),
(n.referrerPolicy = "strict-origin"),
e.id && n.setAttribute("id", e.id),
e &&
e.detectingConflicts &&
e.detectionIgnoreAttr &&
n.setAttributeNode(document.createAttribute(e.detectionIgnoreAttr)),
n
);
}
function L(t) {
var e,
n = [],
r = document,
o = r.documentElement.doScroll,
i = (o ? /^loaded|^c/ : /^loaded|^i|^c/).test(r.readyState);
i ||
r.addEventListener(
"DOMContentLoaded",
(e = function() {
for (
r.removeEventListener("DOMContentLoaded", e), i = 1;
(e = n.shift());
)
e();
})
),
i ? setTimeout(t, 0) : n.push(t);
}
function T(t) {
"undefined" != typeof MutationObserver &&
new MutationObserver(t).observe(document, {
childList: !0,
subtree: !0
});
}
try {
if (window.FontAwesomeKitConfig) {
var x = window.FontAwesomeKitConfig,
M = {
detectingConflicts: x.detectConflictsUntil &&
new Date() <= new Date(x.detectConflictsUntil),
detectionIgnoreAttr: "data-fa-detection-ignore",
fetch: window.fetch,
token: x.token,
XMLHttpRequest: window.XMLHttpRequest,
document: document
},
D = document.currentScript,
N = D ? D.parentElement : document.head;
(function() {
var t =
arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
e =
arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
return "js" === t.method ?
k(t, e) :
"css" === t.method ?
F(t, e, function(t) {
L(t), T(t);
}) :
void 0;
})(x, M)
.then(function(t) {
t.map(function(t) {
try {
N.insertBefore(t, D ? D.nextSibling : null);
} catch (e) {
N.appendChild(t);
}
}),
M.detectingConflicts &&
D &&
L(function() {
D.setAttributeNode(
document.createAttribute(M.detectionIgnoreAttr)
);
var t = (function(t, e) {
var n = document.createElement("script");
return (
e &&
e.detectionIgnoreAttr &&
n.setAttributeNode(
document.createAttribute(e.detectionIgnoreAttr)
),
(n.src = c(t, {
baseFilename: "conflict-detection",
fileSuffix: "js",
subdir: "js",
minify: t.minify.enabled
})),
n
);
})(x, M);
document.body.appendChild(t);
});
})
.catch(function(t) {
console.error("".concat("Font Awesome Kit:", " ").concat(t));
});
}
} catch (t) {
console.error("".concat("Font Awesome Kit:", " ").concat(t));
}
});
#buttonsToolbar button:last-child {
margin: 0;
}
#buttonsToolbar button {
width: 30px;
height: 30px;
margin: 0 5px 0 0;
border: none;
outline: none;
cursor: pointer;
}
#buttonsToolbar {
width: fit-content;
}
#textEditor {
width: 100%;
height: 250px;
margin-top: 5px;
padding: 5px;
color: black;
border: 1px solid rgba(0, 0, 0, .1);
border-radius: 3px;
outline: none;
background-color: white;
box-shadow: 0 8px 18px rgba(0, 0, 0, .1);
}
#buttonsToolbar button.active {
background-color: rgb(214, 214, 214)
}
#textEditor p {
color: black;
}
<form method="post" accept-charset="utf-8">
<div class="input textarea">
<label for="address">Address (200 characters)</label>
<textarea name="businessaddress" id="text-editor" rows="2"></textarea>
</div>
<button class="btn btn-primary float-end" type="submit">Submit</button>
</form>
Better opt in for a more advanced rich text editor
The problem with most lightweight editors like this hey are lacking a lot of useful if not indispensable features like sanitizing pasteboard formating.
So I strongly recommend searching for other alternatives.
Awesome WYSIWYG – A curated list of awesome WYSIWYG editors.

Related

Uncaught TypeError: g(...).block is not a function

Getting this error on the checkout page of WooCommerce store.
checkout.min.js?ver=4.3.1:186 Uncaught TypeError: g(...).block is not a function
at update_checkout_action (checkout.min.js?ver=4.3.1:186)
Points to this line.
g(".woocommerce-checkout-payment,.woocommerce-checkout-review-order-table").block({
I'm new to JS and for the life of me can't figure out a solution. This is the URL for the page http://shannonp12.sg-host.com/checkout/ I'm unable to contact the original developer. Full snippet below.
jQuery(function(g) {
if ("undefined" == typeof wc_checkout_params)
return !1;
var v = {
dirtyInput: !1,
selectedPaymentMethod: !1,
xhr: !1,
$order_review: g("#order_review"),
$checkout_form: g("form.checkout"),
init: function() {
g(document.body).bind("update_checkout", this.update_checkout),
g(document.body).bind("init_checkout", this.init_checkout),
this.$checkout_form.on("click", 'input[name="payment_method"]', this.payment_method_selected),
g(document.body).hasClass("woocommerce-order-pay") && (this.$order_review.on("click", 'input[name="payment_method"]', this.payment_method_selected),
this.$order_review.on("submit", this.submitOrder),
this.$order_review.attr("novalidate", "novalidate")),
this.$checkout_form.attr("novalidate", "novalidate"),
this.$checkout_form.on("submit", this.submit),
this.$checkout_form.on("input validate change", ".input-text, select, input:checkbox", this.validate_field),
this.$checkout_form.on("update", this.trigger_update_checkout),
this.$checkout_form.on("change", 'select.shipping_method, input[name^="shipping_method"], #ship-to-different-address input, .update_totals_on_change select, .update_totals_on_change input[type="radio"], .update_totals_on_change input[type="checkbox"]', this.trigger_update_checkout),
this.$checkout_form.on("change", ".address-field select", this.input_changed),
this.$checkout_form.on("change", ".address-field input.input-text, .update_totals_on_change input.input-text", this.maybe_input_changed),
this.$checkout_form.on("keydown", ".address-field input.input-text, .update_totals_on_change input.input-text", this.queue_update_checkout),
this.$checkout_form.on("change", "#ship-to-different-address input", this.ship_to_different_address),
this.$checkout_form.find("#ship-to-different-address input").change(),
this.init_payment_methods(),
"1" === wc_checkout_params.is_checkout && g(document.body).trigger("init_checkout"),
"yes" === wc_checkout_params.option_guest_checkout && g("input#createaccount").change(this.toggle_create_account).change()
},
init_payment_methods: function() {
var e = g(".woocommerce-checkout").find('input[name="payment_method"]');
1 === e.length && e.eq(0).hide(),
v.selectedPaymentMethod && g("#" + v.selectedPaymentMethod).prop("checked", !0),
0 === e.filter(":checked").length && e.eq(0).prop("checked", !0);
var t = e.filter(":checked").eq(0).prop("id");
1 < e.length && g('div.payment_box:not(".' + t + '")').filter(":visible").slideUp(0),
e.filter(":checked").eq(0).trigger("click")
},
get_payment_method: function() {
return v.$checkout_form.find('input[name="payment_method"]:checked').val()
},
payment_method_selected: function(e) {
if (e.stopPropagation(),
1 < g(".payment_methods input.input-radio").length) {
var t = g("div.payment_box." + g(this).attr("ID"))
, o = g(this).is(":checked");
o && !t.is(":visible") && (g("div.payment_box").filter(":visible").slideUp(230),
o && t.slideDown(230))
} else
g("div.payment_box").show();
g(this).data("order_button_text") ? g("#place_order").text(g(this).data("order_button_text")) : g("#place_order").text(g("#place_order").data("value"));
var c = g('.woocommerce-checkout input[name="payment_method"]:checked').attr("id");
c !== v.selectedPaymentMethod && g(document.body).trigger("payment_method_selected"),
v.selectedPaymentMethod = c
},
toggle_create_account: function() {
g("div.create-account").hide(),
g(this).is(":checked") && (g("#account_password").val("").change(),
g("div.create-account").slideDown())
},
init_checkout: function() {
g(document.body).trigger("update_checkout")
},
maybe_input_changed: function(e) {
v.dirtyInput && v.input_changed(e)
},
input_changed: function(e) {
v.dirtyInput = e.target,
v.maybe_update_checkout()
},
queue_update_checkout: function(e) {
if (9 === (e.keyCode || e.which || 0))
return !0;
v.dirtyInput = this,
v.reset_update_checkout_timer(),
v.updateTimer = setTimeout(v.maybe_update_checkout, "1000")
},
trigger_update_checkout: function() {
v.reset_update_checkout_timer(),
v.dirtyInput = !1,
g(document.body).trigger("update_checkout")
},
maybe_update_checkout: function() {
var e = !0;
if (g(v.dirtyInput).length) {
var t = g(v.dirtyInput).closest("div").find(".address-field.validate-required");
t.length && t.each(function() {
"" === g(this).find("input.input-text").val() && (e = !1)
})
}
e && v.trigger_update_checkout()
},
ship_to_different_address: function() {
g("div.shipping_address").hide(),
g(this).is(":checked") && g("div.shipping_address").slideDown()
},
reset_update_checkout_timer: function() {
clearTimeout(v.updateTimer)
},
is_valid_json: function(e) {
try {
var t = g.parseJSON(e);
return t && "object" == typeof t
} catch (o) {
return !1
}
},
validate_field: function(e) {
var t = g(this)
, o = t.closest(".form-row")
, c = !0
, i = o.is(".validate-required")
, n = o.is(".validate-email")
, r = e.type;
if ("input" === r && o.removeClass("woocommerce-invalid woocommerce-invalid-required-field woocommerce-invalid-email woocommerce-validated"),
"validate" === r || "change" === r) {
if (i && ("checkbox" !== t.attr("type") || t.is(":checked") ? "" === t.val() && (o.removeClass("woocommerce-validated").addClass("woocommerce-invalid woocommerce-invalid-required-field"),
c = !1) : (o.removeClass("woocommerce-validated").addClass("woocommerce-invalid woocommerce-invalid-required-field"),
c = !1)),
n)
if (t.val())
new RegExp(/^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[0-9a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i).test(t.val()) || (o.removeClass("woocommerce-validated").addClass("woocommerce-invalid woocommerce-invalid-email"),
c = !1);
c && o.removeClass("woocommerce-invalid woocommerce-invalid-required-field woocommerce-invalid-email").addClass("woocommerce-validated")
}
},
update_checkout: function(e, t) {
v.reset_update_checkout_timer(),
v.updateTimer = setTimeout(v.update_checkout_action, "5", t)
},
update_checkout_action: function(e) {
if (v.xhr && v.xhr.abort(),
0 !== g("form.checkout").length) {
e = void 0 !== e ? e : {
update_shipping_method: !0
};
var t = g("#billing_country").val()
, o = g("#billing_state").val()
, c = g(":input#billing_postcode").val()
, i = g("#billing_city").val()
, n = g(":input#billing_address_1").val()
, r = g(":input#billing_address_2").val()
, a = t
, u = o
, d = c
, s = i
, m = n
, l = r
, h = g(v.$checkout_form).find(".address-field.validate-required:visible")
, p = !0;
h.length && h.each(function() {
"" === g(this).find(":input").val() && (p = !1)
}),
g("#ship-to-different-address").find("input").is(":checked") && (a = g("#shipping_country").val(),
u = g("#shipping_state").val(),
d = g(":input#shipping_postcode").val(),
s = g("#shipping_city").val(),
m = g(":input#shipping_address_1").val(),
l = g(":input#shipping_address_2").val());
var _ = {
security: wc_checkout_params.update_order_review_nonce,
payment_method: v.get_payment_method(),
country: t,
state: o,
postcode: c,
city: i,
address: n,
address_2: r,
s_country: a,
s_state: u,
s_postcode: d,
s_city: s,
s_address: m,
s_address_2: l,
has_full_address: p,
post_data: g("form.checkout").serialize()
};
if (!1 !== e.update_shipping_method) {
var f = {};
g('select.shipping_method, input[name^="shipping_method"][type="radio"]:checked, input[name^="shipping_method"][type="hidden"]').each(function() {
f[g(this).data("index")] = g(this).val()
}),
_.shipping_method = f
}
g(".woocommerce-checkout-payment,.woocommerce-checkout-review-order-table").block({
message: null,
overlayCSS: {
background: "#fff",
opacity: 0.6
}
}),
v.xhr = g.ajax({
type: "POST",
url: wc_checkout_params.wc_ajax_url.toString().replace("%%endpoint%%", "update_order_review"),
data: _,
success: function(e) {
if (e && !0 === e.reload)
window.location.reload();
else {
g(".woocommerce-NoticeGroup-updateOrderReview").remove();
var t = g("#terms").prop("checked")
, o = {};
if (g(".payment_box :input").each(function() {
var e = g(this).attr("id");
e && (-1 !== g.inArray(g(this).attr("type"), ["checkbox", "radio"]) ? o[e] = g(this).prop("checked") : o[e] = g(this).val())
}),
e && e.fragments && (g.each(e.fragments, function(e, t) {
v.fragments && v.fragments[e] === t || g(e).replaceWith(t),
g(e).unblock()
}),
v.fragments = e.fragments),
t && g("#terms").prop("checked", !0),
g.isEmptyObject(o) || g(".payment_box :input").each(function() {
var e = g(this).attr("id");
e && (-1 !== g.inArray(g(this).attr("type"), ["checkbox", "radio"]) ? g(this).prop("checked", o[e]).change() : -1 !== g.inArray(g(this).attr("type"), ["select"]) ? g(this).val(o[e]).change() : null !== g(this).val() && 0 === g(this).val().length && g(this).val(o[e]).change())
}),
e && "failure" === e.result) {
var c = g("form.checkout");
g(".woocommerce-error, .woocommerce-message").remove(),
e.messages ? c.prepend('<div class="woocommerce-NoticeGroup woocommerce-NoticeGroup-updateOrderReview">' + e.messages + "</div>") : c.prepend(e),
c.find(".input-text, select, input:checkbox").trigger("validate").blur(),
v.scroll_to_notices()
}
v.init_payment_methods(),
g(document.body).trigger("updated_checkout", [e])
}
}
})
}
},
handleUnloadEvent: function(e) {
return -1 === navigator.userAgent.indexOf("MSIE") && !document.documentMode || (e.preventDefault(),
undefined)
},
attachUnloadEventsOnSubmit: function() {
g(window).on("beforeunload", this.handleUnloadEvent)
},
detachUnloadEventsOnSubmit: function() {
g(window).unbind("beforeunload", this.handleUnloadEvent)
},
blockOnSubmit: function(e) {
1 !== e.data()["blockUI.isBlocked"] && e.block({
message: null,
overlayCSS: {
background: "#fff",
opacity: .6
}
})
},
submitOrder: function() {
v.blockOnSubmit(g(this))
},
submit: function() {
v.reset_update_checkout_timer();
var o = g(this);
return o.is(".processing") || !1 !== o.triggerHandler("checkout_place_order") && !1 !== o.triggerHandler("checkout_place_order_" + v.get_payment_method()) && (o.addClass("processing"),
v.blockOnSubmit(o),
v.attachUnloadEventsOnSubmit(),
g.ajaxSetup({
dataFilter: function(e, t) {
if ("json" !== t)
return e;
if (v.is_valid_json(e))
return e;
var o = e.match(/{"result.*}/);
return null === o ? console.log("Unable to fix malformed JSON") : v.is_valid_json(o[0]) ? (console.log("Fixed malformed JSON. Original:"),
console.log(e),
e = o[0]) : console.log("Unable to fix malformed JSON"),
e
}
}),
g.ajax({
type: "POST",
url: wc_checkout_params.checkout_url,
data: o.serialize(),
dataType: "json",
success: function(e) {
v.detachUnloadEventsOnSubmit();
try {
if ("success" !== e.result || !1 === o.triggerHandler("checkout_place_order_success"))
throw "failure" === e.result ? "Result failure" : "Invalid response";
-1 === e.redirect.indexOf("https://") || -1 === e.redirect.indexOf("http://") ? window.location = e.redirect : window.location = decodeURI(e.redirect)
} catch (t) {
if (!0 === e.reload)
return void window.location.reload();
!0 === e.refresh && g(document.body).trigger("update_checkout"),
e.messages ? v.submit_error(e.messages) : v.submit_error('<div class="woocommerce-error">' + wc_checkout_params.i18n_checkout_error + "</div>")
}
},
error: function(e, t, o) {
v.detachUnloadEventsOnSubmit(),
v.submit_error('<div class="woocommerce-error">' + o + "</div>")
}
})),
!1
},
submit_error: function(e) {
g(".woocommerce-NoticeGroup-checkout, .woocommerce-error, .woocommerce-message").remove(),
v.$checkout_form.prepend('<div class="woocommerce-NoticeGroup woocommerce-NoticeGroup-checkout">' + e + "</div>"),
v.$checkout_form.removeClass("processing").unblock(),
v.$checkout_form.find(".input-text, select, input:checkbox").trigger("validate").blur(),
v.scroll_to_notices(),
g(document.body).trigger("checkout_error")
},
scroll_to_notices: function() {
var e = g(".woocommerce-NoticeGroup-updateOrderReview, .woocommerce-NoticeGroup-checkout");
e.length || (e = g(".form.checkout")),
g.scroll_to_notices(e)
}
}
, e = {
init: function() {
g(document.body).on("click", "a.showcoupon", this.show_coupon_form),
g(document.body).on("click", ".woocommerce-remove-coupon", this.remove_coupon),
g("form.checkout_coupon").hide().submit(this.submit)
},
show_coupon_form: function() {
return g(".checkout_coupon").slideToggle(400, function() {
g(".checkout_coupon").find(":input:eq(0)").focus()
}),
!1
},
submit: function() {
var t = g(this);
if (t.is(".processing"))
return !1;
t.addClass("processing").block({
message: null,
overlayCSS: {
background: "#fff",
opacity: .6
}
});
var o = {
security: wc_checkout_params.apply_coupon_nonce,
coupon_code: t.find('input[name="coupon_code"]').val()
};
return g.ajax({
type: "POST",
url: wc_checkout_params.wc_ajax_url.toString().replace("%%endpoint%%", "apply_coupon"),
data: o,
success: function(e) {
g(".woocommerce-error, .woocommerce-message").remove(),
t.removeClass("processing").unblock(),
e && (t.before(e),
t.slideUp(),
g(document.body).trigger("applied_coupon_in_checkout", [o.coupon_code]),
g(document.body).trigger("update_checkout", {
update_shipping_method: !1
}))
},
dataType: "html"
}),
!1
},
remove_coupon: function(e) {
e.preventDefault();
var t = g(this).parents(".woocommerce-checkout-review-order")
, o = g(this).data("coupon");
t.addClass("processing").block({
message: null,
overlayCSS: {
background: "#fff",
opacity: .6
}
});
var c = {
security: wc_checkout_params.remove_coupon_nonce,
coupon: o
};
g.ajax({
type: "POST",
url: wc_checkout_params.wc_ajax_url.toString().replace("%%endpoint%%", "remove_coupon"),
data: c,
success: function(e) {
g(".woocommerce-error, .woocommerce-message").remove(),
t.removeClass("processing").unblock(),
e && (g("form.woocommerce-checkout").before(e),
g(document.body).trigger("update_checkout", {
update_shipping_method: !1
}),
g("form.checkout_coupon").find('input[name="coupon_code"]').val(""))
},
error: function(e) {
wc_checkout_params.debug_mode && console.log(e.responseText)
},
dataType: "html"
})
}
}
, t = {
init: function() {
g(document.body).on("click", "a.showlogin", this.show_login_form)
},
show_login_form: function() {
return g("form.login, form.woocommerce-form--login").slideToggle(),
!1
}
}
, o = {
init: function() {
g(document.body).on("click", "a.woocommerce-terms-and-conditions-link", this.toggle_terms)
},
toggle_terms: function() {
if (g(".woocommerce-terms-and-conditions").length)
return g(".woocommerce-terms-and-conditions").slideToggle(function() {
var e = g(".woocommerce-terms-and-conditions-link");
g(".woocommerce-terms-and-conditions").is(":visible") ? (e.addClass("woocommerce-terms-and-conditions-link--open"),
e.removeClass("woocommerce-terms-and-conditions-link--closed")) : (e.removeClass("woocommerce-terms-and-conditions-link--open"),
e.addClass("woocommerce-terms-and-conditions-link--closed"))
}),
!1
}
};
v.init(),
e.init(),
t.init(),
o.init()
});

Cyclejs input not resetting after redraw

I tried to create a simple todo app with Cyclejs/xstream. The app works fine. Only thing I not able to understand is after adding each todo the input should clear, which is not happening.
todo.js
import {
div, span, p, input, ul, li, button, body
}
from '#cycle/dom'
import xs from 'xstream'
import Utils from './utils'
export function Todo(sources) {
const sinks = {
DOM: view(model(intent(sources)))
}
return sinks
}
function intent(sources) {
return {
addTodo$: sources.DOM.select('input[type=text]').events('keydown').filter((ev) => {
return ev.which == 13 && ev.target.value.trim().length > 0;
}).map((ev) => {
return ev.target.value;
}),
deleteTodo$: sources.DOM.select('.delete').events('click').map((ev) => {
return Number(ev.target.getAttribute('data-id'));
}).filter((id) => {
return !isNaN(id);
}),
completeTodo$: sources.DOM.select('.complete').events('click').map((ev) => {
return Number(ev.target.getAttribute('data-id'));
}).filter((id) => {
return !isNaN(id);
})
};
}
function model(action$) {
let deleteTodo$ = action$.deleteTodo$.map((id) => {
return (holder) => {
let index = Utils.findIndex(holder.currentTodos, 'id', id);
if (index > -1) holder.currentTodos.splice(index, 1);
return {
currentTodos: holder.currentTodos,
value: ''
};
};
});
let completeTodo$ = action$.completeTodo$.map((id) => {
return (holder) => {
let index = Utils.findIndex(holder.currentTodos, 'id', id);
if (index > -1) holder.currentTodos[index].completed = !holder.currentTodos[index].completed;
return {
currentTodos: holder.currentTodos,
value: ''
};
};
});
let addTodo$ = action$.addTodo$.map((item) => {
return (holder) => {
let todo = {
value: item,
id: holder.currentTodos.length + 1,
completed: false
};
holder.currentTodos.push(todo);
return {
currentTodos: holder.currentTodos,
value: ''
};
};
});
return xs.merge(deleteTodo$, addTodo$, completeTodo$)
.fold((holder, modifier) => {
return modifier(holder);
}, {
currentTodos: [],
value: ''
});
}
function view(state$) {
return state$.map((state) => {
console.log(state);
return div({
attrs: {
class: 'todo'
}
}, [
input({
props: {
type: 'text',
value: state.value
}
}),
ul({
attrs: {
class: 'text'
}
}, state.currentTodos.map((todo) => {
return li({
attrs: {
class: `${todo.completed ? 'completed' : 'open'}`
}
}, [
span(todo.value),
button({
attrs: {
class: 'delete',
'data-id': todo.id
}
}, 'XXXXX'),
button({
attrs: {
class: 'complete',
'data-id': todo.id
}
}, 'CCCCC')
]);
}))
]);
});
}
utils.js
var Utils = {
filter: function(array, fn) {
var results = [];
var item;
for (var i = 0, len = array.length; i < len; i++) {
item = array[i];
if (fn(item)) results.push(item);
}
return results;
},
findItem: function(array, fn) {
for (var i = 0, len = array.length; i < len; i++) {
var item = array[i];
if (fn(item)) return item;
}
return null;
},
findIndex: function(array, prop, value) {
var pointerId = -1;
var index = -1;
var top = array.length;
var bottom = 0;
for (var i = array.length - 1; i >= 0; i--) {
index = bottom + (top - bottom >> 1);
pointerId = array[index][prop];
if (pointerId === value) {
return index;
} else if (pointerId < value) {
bottom = index;
} else if (pointerId > value) {
top = index;
}
}
return -1;
}
};
export default Utils;
You need to put hook inside input element. It will work as expected. If you want you can send another default value (in this case it is empty string).
input({
props: {
type: 'text'
},
hook: {
update: (o, n) => n.elm.value = ''
}
}),
#cycle/dom driver should be > 11.0.0 which works with Snabbdom. But if you use earlier version you need:
var Hook = function(){
this.arguments=arguments;
}
Hook.prototype.hook = function(node) {
node.value=this.arguments[0];
}
input({ attributes: {type: 'text'},
'my-hook':new Hook('')
})

Using Classes in Vue.js

I'm relatively new to Vue, so if this is a stupid question I apologize.
Is it possible to use either ES6 classes or a class function in a Vue object? I'm trying to implement an AI for my Tic-Tac-Toe project using the Minimax algorithm, and I need to make a constructor for my States. But in the Vue object, references to 'this' refer to the Vue object itself, even when wrapped in a class function it would seem. So I'm wondering how I could get around this, or if there is an easier way to accomplish this. Thanks!
Here is the link I'm using for the Minimax algo.
And the link to my Codepen.
console.clear();
const log = console.log.bind(console);
const game = new Vue({
el: '#app',
data: {
turn: 'X',
counter: 0,
winner: '',
started: false,
over: false,
header: {
X: 'color',
O: ''
},
sound() {
const tick = new Audio('https://dl.getdropbox.com/s/kgqqnei0yhv3r8n/219069__annabloom__click1.wav')
if(this.over)
tick.play();
},
board: [[{val:'',bg:''}, {val:'',bg:''}, {val:'',bg:''}],
[{val:'',bg:''}, {val:'',bg:''}, {val:'',bg:''}],
[{val:'',bg:''}, {val:'',bg:''}, {val:'',bg:''}]],
windex: [[[0,0], [0,1], [0,2]],
[[1,0], [1,1], [1,2]],
[[2,0], [2,1], [2,2]],
[[0,0], [1,0], [2,0]],
[[0,1], [1,1], [2,1]],
[[0,2], [1,2], [2,2]],
[[0,0], [1,1], [2,2]],
[[0,2], [1,1], [2,0]]],
arr() {
return this.board.map( x => x.map( y => y.val ));
},
winArr() {
return this.windex.map( x => x.map( y => this.board[y[0]][y[1]].val ));
},
check() {
const winArr = this.winArr();
const checkWindex = winArr.map( (x,ind) => {
if( x.every( y => y == 'X' )) return 'X';
if( x.every( y => y == 'O' )) return 'O';
});
if(checkWindex.includes('X'))
this.setWin('X',checkWindex)
else if(checkWindex.includes('O'))
this.setWin('O',checkWindex)
else if(this.counter == 9) {
this.winner = 'DRAW';
setTimeout(() => this.over = true, 0);
};
}
},
methods: {
mark(box) {
this.header[this.turn] = 'color';
if(this.over) return
if(box.val === ''){
box.val = this.turn;
this.turn = this.turn == 'X' ? 'O' : 'X';
}
this.counter++;
this.check();
this.header.X = this.turn == 'X' ? 'color' : '';
this.header.O = this.turn == 'O' ? 'color' : '';
},
setWin(val,arr) {
const inds = this.windex[arr.indexOf(val)];
inds.forEach( x => {
this.board[x[0]][x[1]].bg = 'active';
});
this.winner = val;
setTimeout(() => this.over = true, 0);
},
start(mode) {
this.started = true;
this.counter = 0;
this.board.map( x => x.map( y => { y.val = ''; y.bg = '' }));
this.over = false;
}
}
});

Javascript help needed, store local variable

As Javascript newbie I'm not able to store locally a variable and reuse from Google cache.
I have a counter that starts onClick from zero then increments until a specific number then goes to a new page.
In the new page I need to continue the counter from the previous number.
I can't use cookies since this is for a Chrome extension, so I used storage.local and I set my manifest as follow:
...
"permissions": ["storage", "https://example.com/*", "unlimitedStorage"],
"content_scripts": [
{
"matches": ["https://example.com/*"],
"js": ["js/jquery-2.1.4.min.js", "js/example.js"],
"css": ["css/example.css"]
}
],
...
So basically when I click my button it starts the follow function and it increments this.count
function Button(t, e, i) {
var n = this;
n.$el = t,
n.count = (Record.get(function() {tmf.followBtn.counter()}) > 1 ? Record.get(function() {tmf.followBtn.counter()}) : 0),
n.$title = t.find(".tmf-btn__title"),
n.$subtitle = t.find(".tmf-btn__subtitle"),
n.action = new BulkAction(e, i), n.$el.on("click", function() {
n.$el.addClass("tmf-btn--active"),
n.$title.text(n.count),
n.action.paused ? (n.action.proceed(), n.$subtitle.text("Click to pause")) : (n.action.pause(), n.$subtitle.text("Click to continue"))
})
}
function Profile(t) {
this.$el = $(".ProfileCard:eq(" + t + ")"),
this.isLoaded() && (this.$btn = this.$el.find(".user-actions-follow-button"),
this.id = this.$el.data("user-id") + "-")
}
function BulkAction(t, e) {
this.callback = t,
this.interval = e,
this.paused = !0
}
function gotoPage() {
window.location.replace("https://example.com/newpage/");
}
$.fn.isPresent = function() {
return this.length > 0
};
var USER_ID = $("#user-dropdown").find("[data-user-id]").data("user-id"),
Record = {
storage: chrome.storage.local,
key: USER_ID.toString(),
get: function(t) {
var e = this;
this.storage.get(this.key, function(i) {
e.result = i, t.call()
})
},
set: function() {
this.storage.set(this.result)
},
add: function(t) {
this.result[this.key] ? this.result[this.key] += t : this.result[this.key] = t, this.set()
},
includes: function(t) {
return this.result[this.key] ? this.result[this.key].includes(t) : !1
}
},
tmf = {
init: function() {
var t = this;
t.$el = $("<div>").addClass("tmf animated").appendTo("body")
},
toggle: function() {
var t = this;
this.$el.removeClass("flipInY flipOutY tmf--active"), $(".ProfileCard").length > 10 ? t.$el.load(chrome.extension.getURL("html/actions.html"), {}, function() {
$(".tmf-btn").on("click", function() {
t.$el.addClass("tmf--active")
}), t.followBtn = new Button($(".tmf-btn--follow"), function() {
this.follow()
}, 100), t.unfollowBtn = new Button($(".tmf-btn--unfollow"), function() {
this.unfollow()
}, 100), t.$el.addClass("flipInY");
var e = new MutationObserver(function(e) {
e.forEach(function(e) {
var i = $("#message-drawer").html();
i.includes("66885") && t.followBtn.setIdle()
})
});
e.observe(document.getElementById("message-drawer"), {
subtree: !0,
characterData: !0,
childList: !0
}), $("#tmf_without_exception").on("change", function() {
t.withoutException = this.checked,
this.checked ? (t.followBtn.$subtitle.text("without exception"),t.unfollowBtn.$subtitle.text("without exception")) : (t.followBtn.$subtitle.text("who have never been unfollowed"), t.unfollowBtn.$subtitle.text("who do not follow you"))
})
}) : this.$el.addClass("flipOutY")
},
withoutException: !1
};
$.extend(Button.prototype, {
incrementCount: function() {
this.count++,
this.$title.text(this.count)
},
counter: function() {
return this.count
},
setIdle: function() {
var t = this;
if (!t.action.paused) {
t.action.pause();
}
}
}),
$.extend(Profile.prototype, {
isLoaded: function() {
return this.$el.isPresent()
},
isFollowing: function() {
return this.$el.find(".FollowStatus").isPresent()
},
isProtected: function() {
return this.$el.find(".Icon--protected").isPresent()
},
isNotFollowing: function() {
return !this.isFollowing()
},
isFollowable: function() {
return this.$btn.children(".follow-text").is(":visible")
},
isFollowed: function() {
return this.$btn.children(".following-text").is(":visible")
},
follow: function() {
if (tmf.followBtn.counter() > 1) {
tmf.followBtn.action.pause();
Record.set(function() {tmf.followBtn.counter()});
gotoPage();
};
this.isFollowable() && !this.isProtected() && tmf.followBtn.counter() < 6 && (tmf.withoutException || !Record.includes(this.id) ? (this.click(), tmf.followBtn.incrementCount()) : this.log("warn", "Already unfollowed once"))
},
unfollow: function() {
this.isFollowed() && (tmf.withoutException || this.isNotFollowing()) && (this.click(), tmf.unfollowBtn.incrementCount(), Record.add(this.id))
},
click: function() {
this.log("success", 'Clicked on "' + this.$btn.children(":visible").text().trim() + '"'), this.$btn.click(), this.clicked = !0
},
log: function(t, e) {
$("<div>").addClass("tmf-log").addClass("tmf-log--" + t).text(e).insertBefore(this.$el.find(".ProfileCard-bio"))
}
}),
$.extend(BulkAction.prototype, {
nth: 0,
loadAttempts: 0,
_loadProfiles: function() {
this.loadAttempts < 10 && (this.last.$btn.focus(), this.loadAttempts++, this._sleep(700))
},
_sleep: function(t) {
var e = this;
setTimeout(function() {
e.run()
}, t)
},
run: function() {
if (!this.paused) {
var t = new Profile(this.nth);
t.isLoaded() ? (this.loadAttempts = 0, this.callback.call(t), this.last = t, this.nth++, t.clicked ? this._sleep(this.interval) : this.run()) : this._loadProfiles()
}
},
pause: function() {
this.paused = !0
},
proceed: function() {
this.paused = !1, this.run()
}
}),
Record.get(function() {
tmf.init(), tmf.toggle()
});
var observer = new MutationObserver(function(t) {
t.forEach(function(t) {
tmf.toggle()
})
});
$(".tmf-btn--close").click(function(){
$(".flipInY").hide();
});
observer.observe(document.querySelector("head > title"), {
subtree: !0,
characterData: !0,
childList: !0
});
I need to store locally my counter, so as you can see I tried to set it as:
Record.set(function() {tmf.followBtn.counter()}); inside my follow function.
Then I tried to get it from my Button function as:
n.count = (Record.get(function() {tmf.followBtn.counter()}) > 1 ? Record.get(function() {tmf.followBtn.counter()}) : 0),
Why all the time I reload the page, the counter starts from zero?

How does the new Apple page fade in the image?

Apple changed their home page with a fade in effect that loads fast. Is this HTML 5 or jQuery?
Does anyone know how they did this?
It is JavaScript. HTML5 is a markup language - it doesn't do dynamic things. But the way people are throwing around the term, you'd think it could cure world hunger.
It looks like they use the Prototype library - probably for legacy reasons, now that jQuery has gained more traction. Or maybe they just prefer that library.
In plain JavaScript, you can fade a div with window.setInterval() and animating style.opacity.
With this bit of javascript --> http://images.apple.com/global/scripts/ac_blackout.js.
Here it is after a run through http://jsbeautifier.org/:
AC.Blackout = Class.create({
defaultOptions: {
duration: 1.25,
delay: 2,
showOnce: false,
showWhenReferredByApple: true
},
initialize: function (c, a, b) {
this.uniqueIdentifier = a || Math.floor(Math.random() * 1000000);
this.options = Object.extend(Object.clone(this.defaultOptions), b);
if (!this.shouldShow()) {
return false
}
this._addBodyClass();
Event.onDOMReady(function () {
this.og = {};
this.og.element = $(c);
this.bo = {};
this.bo.offsets = this.og.element ? this.og.element.cumulativeOffset() : [0, 0];
this.images = [];
if (this.options.showOnce) {
this._setHasShown()
}
this._create();
this.fade.bind(this).delay(this.options.delay)
}.bind(this))
},
addImage: function (b, a) {
this.preloadImage(b);
if ( !! this._acceptImages) {
this._addImage(false, b, a)
} else {
this._boundAddImage = this._addImage.bindAsEventListener(this, b, a);
Event.observe(document.body, "ACBlackout:acceptImages", this._boundAddImage)
}
},
preloadImage: function (c) {
var b = function (d) {
delete a
};
var a = new Image();
a.onload = b;
a.src = c
},
_addImage: function (a, c, b) {
if (typeof this.images == "undefined") {
return false
}
this.images.push(new AC.Blackout.Image(this.bo, c, b))
},
wasReferredByApple: function () {
if (typeof this._wasReferredByApple !== "undefined") {
return this._wasReferredByApple
}
this._wasReferredByApple = document.referrer.match(/^\w*:\/\/[^\.]*.apple.com/);
if ( !! document.referrer.match(/\/home/)) {
return false
}
return this._wasReferredByApple
},
shouldShow: function () {
if (typeof this._shouldShow !== "undefined") {
return this._shouldShow
}
if (/msie|MSIE 6/.test(navigator.userAgent)) {
return this._shouldShow = false
}
this._shouldShow = true;
if (this.options.showOnce) {
if (!this.options.showWhenReferredByApple) {
if (!this.wasReferredByApple()) {
return this._shouldShow = true
}
}
try {
typeof localStorage
} catch (b) {
return this._shouldShow = false
}
if (typeof localStorage !== "undefined") {
try {
var a = localStorage.getItem("ACBlackout-" + this.uniqueIdentifier);
this._shouldShow = (a == null) ? true : false
} catch (b) {
return this._shouldShow = false
}
} else {
if ("addBehavior" in document.body) {
document.body.addBehavior("#default#userData");
document.body.load("ACBlackout");
this._shouldShow = document.body.getAttribute("ACBlackout-" + this.uniqueIdentifier) == null ? true : false
}
}
} else {
if (!this.options.showWhenReferredByApple) {
if ( !! this.wasReferredByApple()) {
this._shouldShow = false
}
}
}
return this._shouldShow
},
_addBodyClass: function () {
document.body.className += " ACBlackoutBody"
},
_setHasShown: function () {
var a = new Date;
a = a.getTime();
try {
typeof localStorage
} catch (b) {
return true
}
if (typeof localStorage !== "undefined") {
try {
localStorage.setItem("ACBlackout-" + this.uniqueIdentifier, a)
} catch (b) {
return true
}
} else {
if ("addBehavior" in document.body) {
document.body.addBehavior("#default#userData");
document.body.setAttribute("ACBlackout-" + this.uniqueIdentifier, a);
document.body.save("ACBlackout");
return true
} else {
return true
}
}
},
_create: function () {
this.bo.height = document.documentElement.clientHeight > document.body.scrollHeight ? document.documentElement.clientHeight : document.body.scrollHeight;
if ($("ACBlackout")) {
this.bo.element = $("ACBlackout")
} else {
this.bo.element = new Element("div", {
id: "ACBlackout",
"class": "ACBlackout",
style: "height: " + this.bo.height + "px;"
})
}
this._acceptImages = true;
Event.fire(document.body, "ACBlackout:acceptImages", true);
if (AC.Detector.isCSSAvailable("transition")) {
this.bo.element.setVendorPrefixStyle("transition", this.options.duration + "s opacity ease-in")
}
if (AC.Detector.isIE()) {
Element.insert(document.body, {
bottom: this.bo.element
})
} else {
Element.insert(document.body, {
top: this.bo.element
})
}
Element.removeClassName(document.body, "ACBlackoutBody")
},
fade: function () {
if (AC.Detector.isCSSAvailable("transition")) {
var b = function (c) {
c.target.hide();
c.target.removeVendorEventListener("transitionEnd", a)
};
var a = b.bindAsEventListener(this);
this.bo.element.addVendorEventListener("transitionEnd", a);
this.bo.element.setStyle("opacity: 0;")
} else {
this.bo.element.fade({
duration: this.options.duration
})
}
}
});
AC.Blackout.Image = Class.create({
defaultOptions: {
offsets: [0, 0],
dimensions: false,
duration: 0.75,
delay: 0
},
initialize: function (b, c, a) {
this.options = Object.extend(Object.clone(this.defaultOptions), a);
this.bo = b;
this.src = c;
this._create();
this.fadeIn.bind(this).delay(this.options.delay)
},
_create: function () {
this.left = this.options.offsets[0];
this.top = this.bo.offsets[1] + this.options.offsets[1];
this.main = new Element("div", {
"class": "ACBlackoutMain"
});
this.img = new Element("img", {
src: this.src,
"class": "ACBlackoutImg",
style: "top: " + this.top + "px; left: " + this.left + "px;"
});
if (this.options.dimensions) {
this.img.setStyle("width: " + this.options.dimensions[0] + "px; height: " + this.options.dimensions[1] + "px;")
}
if (AC.Detector.isCSSAvailable("transition")) {
this.img.setStyle("opacity: 0");
this.img.setVendorPrefixStyle("transition", this.options.duration + "s opacity ease-in")
} else {
this.img.hide()
}
this.bo.element.insert(this.main);
this.main.insert(this.img)
},
fadeIn: function () {
if (AC.Detector.isCSSAvailable("transition")) {
this.img.setStyle("opacity: 1;")
} else {
this.img.appear({
duration: this.options.duration
})
}
}
});

Categories