I have a text box that will only show half of the text inputted, unless the text box is a bigger size. Before I type, the cursor is half way showing, when I'm typing, it is normal, then after I type, it goes back to only half way showing. The text box is attached to Java Script that makes it so the inputted amount automatically turns into a dollar amount, would that affect it?
JavaScript:
$(document).ready(function () {
$("input[type=text].currenciesOnly").live('keydown', currenciesOnly)
.live('blur', function () {
$(this).formatCurrency();
});
});
// JavaScript I wrote to limit what types of input are allowed to be keyed into a textbox
var allowedSpecialCharKeyCodes = [46, 8, 37, 39, 35, 36, 9];
var numberKeyCodes = [44, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105];
var commaKeyCode = [188];
var decimalKeyCode = [190, 110];
function numbersOnly(event) {
var legalKeyCode = (!event.shiftKey && !event.ctrlKey && !event.altKey) && (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0 || jQuery.inArray(event.keyCode, numberKeyCodes) >= 0);
if (legalKeyCode === false) event.preventDefault();
}
function numbersAndCommasOnly(event) {
var legalKeyCode = (!event.shiftKey && !event.ctrlKey && !event.altKey) && (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0 || jQuery.inArray(event.keyCode, numberKeyCodes) >= 0 || jQuery.inArray(event.keyCode, commaKeyCode) >= 0);
if (legalKeyCode === false) event.preventDefault();
}
function decimalsOnly(event) {
var legalKeyCode = (!event.shiftKey && !event.ctrlKey && !event.altKey) && (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0 || jQuery.inArray(event.keyCode, numberKeyCodes) >= 0 || jQuery.inArray(event.keyCode, commaKeyCode) >= 0 || jQuery.inArray(event.keyCode, decimalKeyCode) >= 0);
if (legalKeyCode === false) event.preventDefault();
}
function currenciesOnly(event) {
var legalKeyCode = (!event.shiftKey && !event.ctrlKey && !event.altKey) && (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0 || jQuery.inArray(event.keyCode, numberKeyCodes) >= 0 || jQuery.inArray(event.keyCode, commaKeyCode) >= 0 || jQuery.inArray(event.keyCode, decimalKeyCode) >= 0);
// Allow for $
if (!legalKeyCode && event.shiftKey && event.keyCode == 52) legalKeyCode = true;
if (legalKeyCode === false) event.preventDefault();
}
// jQuery formatCurrency plugin... see http://code.google.com/p/jquery-formatcurrency/
(function ($) {
$.formatCurrency = {};
$.formatCurrency.regions = [];
$.formatCurrency.regions[""] = {
symbol: "$",
positiveFormat: "%s%n",
negativeFormat: "(%s%n)",
decimalSymbol: ".",
digitGroupSymbol: ",",
groupDigits: true
};
$.fn.formatCurrency = function (destination, settings) {
if (arguments.length == 1 && typeof destination !== "string") {
settings = destination;
destination = false;
}
var defaults = {
name: "formatCurrency",
colorize: false,
region: "",
global: true,
roundToDecimalPlace: 2,
eventOnDecimalsEntered: false
};
defaults = $.extend(defaults, $.formatCurrency.regions[""]);
settings = $.extend(defaults, settings);
if (settings.region.length > 0) {
settings = $.extend(settings, getRegionOrCulture(settings.region));
}
settings.regex = generateRegex(settings);
return this.each(function () {
$this = $(this);
var num = "0";
num = $this[$this.is("input, select, textarea") ? "val" : "html"]();
if (num.search("\\(") >= 0) {
num = "-" + num;
}
if (num === "" || (num === "-" && settings.roundToDecimalPlace === -1)) {
return;
}
if (isNaN(num)) {
num = num.replace(settings.regex, "");
if (num === "" || (num === "-" && settings.roundToDecimalPlace === -1)) {
return;
}
if (settings.decimalSymbol != ".") {
num = num.replace(settings.decimalSymbol, ".");
}
if (isNaN(num)) {
num = "0";
}
}
var numParts = String(num).split(".");
var isPositive = (num == Math.abs(num));
var hasDecimals = (numParts.length > 1);
var decimals = (hasDecimals ? numParts[1].toString() : "0");
var originalDecimals = decimals;
num = Math.abs(numParts[0]);
num = isNaN(num) ? 0 : num;
if (settings.roundToDecimalPlace >= 0) {
decimals = parseFloat("1." + decimals);
decimals = decimals.toFixed(settings.roundToDecimalPlace);
if (decimals.substring(0, 1) == "2") {
num = Number(num) + 1;
}
decimals = decimals.substring(2);
}
num = String(num);
if (settings.groupDigits) {
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ;
i++) {
num = num.substring(0, num.length - (4 * i + 3)) + settings.digitGroupSymbol + num.substring(num.length - (4 * i + 3));
}
}
if ((hasDecimals && settings.roundToDecimalPlace == -1) || settings.roundToDecimalPlace > 0) {
num += settings.decimalSymbol + decimals;
}
var format = isPositive ? settings.positiveFormat : settings.negativeFormat;
var money = format.replace(/%s/g, settings.symbol);
money = money.replace(/%n/g, num);
var $destination = $([]);
if (!destination) {
$destination = $this;
} else {
$destination = $(destination);
}
$destination[$destination.is("input, select, textarea") ? "val" : "html"](money);
if (hasDecimals && settings.eventOnDecimalsEntered && originalDecimals.length > settings.roundToDecimalPlace) {
$destination.trigger("decimalsEntered", originalDecimals);
}
if (settings.colorize) {
$destination.css("color", isPositive ? "black" : "red");
}
});
};
$.fn.toNumber = function (settings) {
var defaults = $.extend({
name: "toNumber",
region: "",
global: true
}, $.formatCurrency.regions[""]);
settings = jQuery.extend(defaults, settings);
if (settings.region.length > 0) {
settings = $.extend(settings, getRegionOrCulture(settings.region));
}
settings.regex = generateRegex(settings);
return this.each(function () {
var method = $(this).is("input, select, textarea") ? "val" : "html";
$(this)[method]($(this)[method]().replace("(", "(-").replace(settings.regex, ""));
});
};
$.fn.asNumber = function (settings) {
var defaults = $.extend({
name: "asNumber",
region: "",
parse: true,
parseType: "Float",
global: true
}, $.formatCurrency.regions[""]);
settings = jQuery.extend(defaults, settings);
if (settings.region.length > 0) {
settings = $.extend(settings, getRegionOrCulture(settings.region));
}
settings.regex = generateRegex(settings);
settings.parseType = validateParseType(settings.parseType);
var method = $(this).is("input, select, textarea") ? "val" : "html";
var num = $(this)[method]();
num = num ? num : "";
num = num.replace("(", "(-");
num = num.replace(settings.regex, "");
if (!settings.parse) {
return num;
}
if (num.length === 0) {
num = "0";
}
if (settings.decimalSymbol != ".") {
num = num.replace(settings.decimalSymbol, ".");
}
return window["parse" + settings.parseType](num);
};
function getRegionOrCulture(region) {
var regionInfo = $.formatCurrency.regions[region];
if (regionInfo) {
return regionInfo;
} else {
if (/(\w+)-(\w+)/g.test(region)) {
var culture = region.replace(/(\w+)-(\w+)/g, "$1");
return $.formatCurrency.regions[culture];
}
}
return null;
}
function validateParseType(parseType) {
switch (parseType.toLowerCase()) {
case "int":
return "Int";
case "float":
return "Float";
default:
throw "invalid parseType";
}
}
function generateRegex(settings) {
if (settings.symbol === "") {
return new RegExp("[^\\d" + settings.decimalSymbol + "-]", "g");
} else {
var symbol = settings.symbol.replace("$", "\\$").replace(".", "\\.");
return new RegExp(symbol + "|[^\\d" + settings.decimalSymbol + "-]", "g");
}
}
})(jQuery);
Textbox:
<input type="text" class="currenciesOnly" />
Code from free open source site
With help from #Eyal and #LeoFarmer somewhere within bootstrap, the line-height was affecting it. So I set line-height to normal in the css for the textbox:
.currenciesOnly {
line-height: normal;
}
Related
I was able to get some help from a previous post where I wanted to highlight words dynamically as a user entered text.
The previous condition would highlight a word if it began with "t", now I want to update this condition to highlight any words that meet a condition based on dictionary values (I call JavaScript's built in object a dictionary).
For example, if I have a dictionary dict = {"test": 5.0, "check": 4.0, "stop": -1.5, "fair": 2.0} how would I have the script highlight words whose value was greater than 2.0?
Failed code:
dict = {"test": 5.0, "check": 4.0, "stop": -1.5, "fair": 2.0}
function highlighter(ev) {
// Get current cursor position
const currpos = getSelectionDirection(ev) !== 'forward' ? getSelectionStart(ev) : getSelectionEnd(ev);
// Change innerHTML to innerText, you
// dont need to parse HTML code here
var content = ev.innerText;
var tokens = content.split(" ");
for (var i = 0; i < tokens.length; i++) {
if (dict[tokens[i][0]] > 2.0) {
tokens[i] = "<mark style='background-color:red; color:white;'>" + tokens[i] + "</mark>";
}
}
ev.innerHTML = tokens.join(" ");
// Set cursor on its proper position
setSelectionRange(ev, currpos, currpos);
}
/* NOT REQUIRED AT ALL, JUST TO MAKE INTERACTION MORE PLEASANT */
.container {
outline: none;
border: 3px solid black;
height: 100px;
width: 400px;
}
<div class="container" onkeypress=highlighter(this) contenteditable>
</div>
<script>
// Usage:
// var x = document.querySelector('[contenteditable]');
// var caretPosition = getSelectionDirection(x) !== 'forward' ? getSelectionStart(x) : getSelectionEnd(x);
// setSelectionRange(x, caretPosition + 1, caretPosition + 1);
// var value = getValue(x);
// it will not work with "<img /><img />" and, perhaps, in many other cases.
function isAfter(container, offset, node) {
var c = node;
while (c.parentNode != container) {
c = c.parentNode;
}
var i = offset;
while (c != null && i > 0) {
c = c.previousSibling;
i -= 1;
}
return i > 0;
}
function compareCaretPositons(node1, offset1, node2, offset2) {
if (node1 === node2) {
return offset1 - offset2;
}
var c = node1.compareDocumentPosition(node2);
if ((c & Node.DOCUMENT_POSITION_CONTAINED_BY) !== 0) {
return isAfter(node1, offset1, node2) ? +1 : -1;
} else if ((c & Node.DOCUMENT_POSITION_CONTAINS) !== 0) {
return isAfter(node2, offset2, node1) ? -1 : +1;
} else if ((c & Node.DOCUMENT_POSITION_FOLLOWING) !== 0) {
return -1;
} else if ((c & Node.DOCUMENT_POSITION_PRECEDING) !== 0) {
return +1;
}
}
function stringifyElementStart(node, isLineStart) {
if (node.tagName.toLowerCase() === 'br') {
if (true) {
return '\n';
}
}
if (node.tagName.toLowerCase() === 'div') { // Is a block-level element?
if (!isLineStart) { //TODO: Is not at start of a line?
return '\n';
}
}
return '';
}
function* positions(node, isLineStart = true) {
console.assert(node.nodeType === Node.ELEMENT_NODE);
var child = node.firstChild;
var offset = 0;
yield {node: node, offset: offset, text: stringifyElementStart(node, isLineStart)};
while (child != null) {
if (child.nodeType === Node.TEXT_NODE) {
yield {node: child, offset: 0/0, text: child.data};
isLineStart = false;
} else {
isLineStart = yield* positions(child, isLineStart);
}
child = child.nextSibling;
offset += 1;
yield {node: node, offset: offset, text: ''};
}
return isLineStart;
}
function getCaretPosition(contenteditable, textPosition) {
var textOffset = 0;
var lastNode = null;
var lastOffset = 0;
for (var p of positions(contenteditable)) {
if (p.text.length > textPosition - textOffset) {
return {node: p.node, offset: p.node.nodeType === Node.TEXT_NODE ? textPosition - textOffset : p.offset};
}
textOffset += p.text.length;
lastNode = p.node;
lastOffset = p.node.nodeType === Node.TEXT_NODE ? p.text.length : p.offset;
}
return {node: lastNode, offset: lastOffset};
}
function getTextOffset(contenteditable, selectionNode, selectionOffset) {
var textOffset = 0;
for (var p of positions(contenteditable)) {
if (selectionNode.nodeType !== Node.TEXT_NODE && selectionNode === p.node && selectionOffset === p.offset) {
return textOffset;
}
if (selectionNode.nodeType === Node.TEXT_NODE && selectionNode === p.node) {
return textOffset + selectionOffset;
}
textOffset += p.text.length;
}
return compareCaretPositons(selectionNode, selectionOffset, contenteditable, 0) < 0 ? 0 : textOffset;
}
function getValue(contenteditable) {
var value = '';
for (var p of positions(contenteditable)) {
value += p.text;
}
return value;
}
function setSelectionRange(contenteditable, start, end) {
var selection = window.getSelection();
var s = getCaretPosition(contenteditable, start);
var e = getCaretPosition(contenteditable, end);
selection.setBaseAndExtent(s.node, s.offset, e.node, e.offset);
}
//TODO: Ctrl+A - rangeCount is 2
function getSelectionDirection(contenteditable) {
var selection = window.getSelection();
var c = compareCaretPositons(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
return c < 0 ? 'forward' : 'none';
}
function getSelectionStart(contenteditable) {
var selection = window.getSelection();
var c = compareCaretPositons(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
return c < 0 ? getTextOffset(contenteditable, selection.anchorNode, selection.anchorOffset) : getTextOffset(contenteditable, selection.focusNode, selection.focusOffset);
}
function getSelectionEnd(contenteditable) {
var selection = window.getSelection();
var c = compareCaretPositons(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
return c < 0 ? getTextOffset(contenteditable, selection.focusNode, selection.focusOffset) : getTextOffset(contenteditable, selection.anchorNode, selection.anchorOffset);
}
</script>
Check below code I used this Cool js lib jQuery highlightTextarea and as per your requirements, I loop through your dict object and push only those words that have a value greater than 2.0.
dict = {"test": 5.0, "check": 4.0, "stop": -1.5, "fair": 2.0}
var words = [];
Object.keys(dict).forEach(function(key) {
if( dict[key] > 2 ){
words.push(key);
}
});
$('textarea').highlightTextarea({
words: words,
caseSensitive: false
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://garysieling.github.io/jquery-highlighttextarea/dist/jquery-ui/themes/smoothness/jquery-ui.min.css">
<link rel="stylesheet" href="http://garysieling.github.io/jquery-highlighttextarea/dist/jquery-highlighttextarea/jquery.highlighttextarea.min.css">
<script src="http://garysieling.github.io/jquery-highlighttextarea/dist/jquery-ui/ui/minified/jquery-ui.min.js"></script>
<script src="http://garysieling.github.io/jquery-highlighttextarea/dist/jquery-highlighttextarea/jquery.highlighttextarea.min.js"></script>
<textarea id="demo-case" cols="50" rows="3" style="background: none;" spellcheck="true">This is a test you can check or stop it will be fair enough.</textarea>
More options here http://garysieling.github.io/jquery-highlighttextarea/#options
Other example here http://garysieling.github.io/jquery-highlighttextarea/examples.html
I have the two functions match and and total working properly. I want the function total project match to divide the first function over the second function multiply times 100. the last function isn't working!
Here is my code so far :
matchContribution.subscribe(function (newValue) {
if (newValue != undefined && newValue != '') {
matchContribution(formatInt(newValue));
var dataValue = Number(matchContribution().replace(/\,/g, ''));
if (dataValue > 999999999999.99 || dataValue < 0) {
matchContribution('');
}
if (loading == false) {
sendCommand('SAVE');
}
}
});
var totalProjectCost = ko.computed(function () {
var total = 0;
var hasUserInput = false;
if (grantRequest() != '' && grantRequest() != undefined) {
hasUserInput = true;
total = total + Number(String(grantRequest()).replace(/\,/g, ''));
}
if (matchContribution() != '' && matchContribution() != undefined) {
hasUserInput = true;
total = total + Number(String(matchContribution()).replace(/\,/g, ''));
}
if (total == 0) {
if (!hasUserInput)
return '';
else
return formatInt('0');
}
else {
if (loading == false) {
sendCommand('SAVE');
}
return formatInt(total);
}
});
var totalProjectMatch = matchContribution()/totalProjectCost();
if(totalProjectMatch>=0)
totalProjectMatch = Math.floor(totalProjectMatch);
else
totalProjectMatch = Math.ceil(totalProjectMatch);
var totalProjectMatch = ko.computed(function () {
var total = 0;
var hasUserInput = false;
if ((grantRequest() != '' && grantRequest() != undefined) && (matchContribution() != '' && matchContribution() != undefined) && (totalProjectCost() != '' && totalProjectCost() != undefined)) {
hasUserInput = true;
total = Number(String(matchContribution()).replace(/\,/g, '')) / Number(String(totalProjectCost()).replace(/\,/g, ''));
total = total * 100;
}
if (total == 0) {
if (!hasUserInput)
return '';
else
return formatInt('0');
}
else {
if (loading == false) {
sendCommand('SAVE');
}
return formatNumber(total);
}
});
I solved the problem! Thanks a lot! Hope that helps other people.
On my HTML page, I need to have a line with text that rolls "infinitely" on the page, e.g.
"Hello World ... Hello World ... Hello World ... Hello World ..."
Sort of like a ticker tape, but with the same text's beginning rolling into its end w/o a gap.
I've tried using animation: marquee CSS style, I can get the text roll, then jump back, then roll again, but that's not what I need.
Is this possible with CSS? JS would be OK, if there is a working solution.
Try here "text rolling" working with text & images and mouse effects(js+css)
http://www.dynamicdrive.com/dynamicindex2/crawler/index.htm
Are you open to using a lib that does this?
This one here: http://www.cssscript.com/marquee-like-horizontal-scroller-with-pure-javascript-marquee-js/ does a good job.
$(document).ready(function() {
new Marquee('example', {
// once or continuous
continuous: true,
// 'rtl' or 'ltr'
direction: 'rtl',
// pause between loops
delayAfter: 1000,
// when to start
delayBefore: 0,
// scroll speed
speed: 0.5,
// loops
loops: -1
});
});
////////////////////////////// LIBRARY BELOW ///////
// See: http://www.cssscript.com/marquee-like-horizontal-scroller-with-pure-javascript-marquee-js/
/*
Vanilla Javascript Marquee
Version: 0.1.0
Author: Robert Bossaert <https://github.com/robertbossaert>
Example call:
new Marquee('element');
new Marquee('element', {
direction: 'rtl',
});
*/
var Marquee = function(element, defaults) {
"use strict";
var elem = document.getElementById(element),
options = (defaults === undefined) ? {} : defaults,
continuous = options.continuous || true, // once or continuous
delayAfter = options.delayAfter || 1000, // pause between loops
delayBefore = options.delayBefore || 0, // when to start
direction = options.direction || 'ltr', // ltr or rtl
loops = options.loops || -1,
speed = options.speed || 0.5,
timer = null,
milestone = 0,
marqueeElem = null,
elemWidth = null,
self = this,
ltrCond = 0,
loopCnt = 0,
start = 0,
process = null,
constructor = function(elem) {
// Build html
var elemHTML = elem.innerHTML,
elemNode = elem.childNodes[1] || elem;
elemWidth = elemNode.offsetWidth;
marqueeElem = '<div>' + elemHTML + '</div>';
elem.innerHTML = marqueeElem;
marqueeElem = elem.getElementsByTagName('div')[0];
elem.style.overflow = 'hidden';
marqueeElem.style.whiteSpace = 'nowrap';
marqueeElem.style.position = 'relative';
if (continuous === true) {
marqueeElem.innerHTML += elemHTML;
marqueeElem.style.width = '200%';
if (direction === 'ltr') {
start = -elemWidth;
}
} else {
ltrCond = elem.offsetWidth;
if (direction === 'rtl') {
milestone = ltrCond;
}
}
if (direction === 'ltr') {
milestone = -elemWidth;
} else if (direction === 'rtl') {
speed = -speed;
}
self.start();
return marqueeElem;
}
this.start = function() {
process = window.setInterval(function() {
self.play();
});
};
this.play = function() {
// beginning
marqueeElem.style.left = start + 'px';
start = start + speed;
if (start > ltrCond || start < -elemWidth) {
start = milestone;
loopCnt++;
if (loops !== -1 && loopCnt >= loops) {
marqueeElem.style.left = 0;
}
}
}
this.end = function() {
window.clearInterval(process);
}
// Init plugin
marqueeElem = constructor(elem);
}
body {
background: #edf3f9;
color: #3f4f5f;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.container {
margin: 0 auto;
width: 800px;
}
header {
border-bottom: 2px solid #3f4f5f;
padding: 6.25em 0 3.95em;
text-align: center;
width: 100%;
}
header h1 {
margin: 0 0 10px;
}
.example {
padding: 3em 0;
}
h2 {
text-align: center;
}
pre {
background: #f5f2f0;
color: #000;
font-family: Consolas, Monaco, 'Andale Mono', monospace;
line-height: 26px;
padding: 1em;
text-shadow: 0 1px white;
white-space: pre-wrap;
}
pre span.string {
color: #690;
}
pre span.number {
color: #905;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example">
The quick brown fox ran over to the bar to drink some water. He walked up to the bar tender and said: blah blah blah.
</div>
Here is a demo based upon the lib that Dreamer posted.
I didn't like how it set inline styles on the element or how it used cookies to store past settings so I removed that in the crawler.js code.
This is a pretty old library (ie5 is mentioned (!)) but it seems to do the trick.
$(function() {
marqueeInit({
uniqueid: 'mycrawler',
style: {
},
inc: 5, //speed - pixel increment for each iteration of this marquee's movement
mouse: 'cursor driven', //mouseover behavior ('pause' 'cursor driven' or false)
moveatleast: 2,
neutral: 150,
persist: true,
savedirection: true
});
});
//////////////// CRAWLER.JS FOLLOWS ///////////
/* Text and/or Image Crawler Script v1.53 (c)2009-2012 John Davenport Scheuer
as first seen in http://www.dynamicdrive.com/forums/
username: jscheuer1 - This Notice Must Remain for Legal Use
updated: 4/2011 for random order option, more (see below)
*/
/* Update 4/2011 to v1.5 - Adds optional random property. Set it to true to use.
Fixes browser crash from empty crawlers, ad and image blocking software/routines.
Fixes behavior in some IE of breaking script if an image is missing.
Adds alt attributes to images without them to aid in diagnosis of missing/corrupt
images. This may be disabled with the new optional noAddedAlt property set to true.
Internal workings enhanced for greater speed of execution, less memory usage.
*/
/* Update 11/2011 - Detect and randomize td elements within a single table with a single tr */
// updated 7/2012 to 1.51 for optional integration with 3rd party initializing scripts -
// ref: http://www.dynamicdrive.com/forums/showthread.php?p=278161#post278161
// updated 8/2012 to 1.52 for greater compatibility with IE in Quirks Mode
/* Update 10/2012 to v1.53 - Adds optional persist property to have the crawler remember its
position and direction page to page and on page reload. To enable it in the marqueeInit set
persist: true,
*/
///////////////// No Need to Edit - Configuration is Done in the On Page marqueeInit call(s) /////////////////
function marqueeInit(config) {
if (!document.createElement) return;
marqueeInit.ar.push(config);
marqueeInit.run(config.uniqueid);
}
(function() {
if (!document.createElement) return;
if (typeof opera === 'undefined') {
window.opera = false;
}
marqueeInit.ar = [];
document.write('<style type="text/css">.marquee{white-space:nowrap;overflow:hidden;visibility:hidden;}' +
'#marq_kill_marg_bord{border:none!important;margin:0!important;}<\/style>');
var c = 0,
tTRE = [/^\s*$/, /^\s*/, /\s*$/, /[^\/]+$/],
req1 = {
'position': 'relative',
'overflow': 'hidden'
},
defaultconfig = {
style: { //default style object for marquee containers without configured style
'margin': '0 auto'
},
direction: 'left',
inc: 2, //default speed - pixel increment for each iteration of a marquee's movement
mouse: 'pause' //default mouseover behavior ('pause' 'cursor driven' or false)
},
dash, ie = false,
oldie = 0,
ie5 = false,
iever = 0;
/*#cc_on #*/
/*#if(#_jscript_version >= 5)
ie = true;
try{document.documentMode = 2000}catch(e){};
iever = Math.min(document.documentMode, navigator.appVersion.replace(/^.*MSIE (\d+\.\d+).*$/, '$1'));
if(iever < 6)
oldie = 1;
if(iever < 5.5){
Array.prototype.push = function(el){this[this.length] = el;};
ie5 = true;
dash = /(-(.))/;
String.prototype.encamel = function(s, m){
s = this;
while((m = dash.exec(s)))
s = s.replace(m[1], m[2].toUpperCase());
return s;
};
}
#end #*/
if (!ie5) {
dash = /-(.)/g;
function toHump(a, b) {
return b.toUpperCase();
};
String.prototype.encamel = function() {
return this.replace(dash, toHump);
};
}
if (ie && iever < 8) {
marqueeInit.table = [];
window.attachEvent('onload', function() {
marqueeInit.OK = true;
var i = -1,
limit = marqueeInit.table.length;
while (++i < limit)
marqueeInit.run(marqueeInit.table[i]);
});
}
function intable(el) {
while ((el = el.parentNode))
if (el.tagName && el.tagName.toLowerCase() === 'table')
return true;
return false;
};
marqueeInit.run = function(id) {
if (ie && !marqueeInit.OK && iever < 8 && intable(document.getElementById(id))) {
marqueeInit.table.push(id);
return;
}
if (!document.getElementById(id))
setTimeout(function() {
marqueeInit.run(id);
}, 300);
else
new Marq(c++, document.getElementById(id));
}
function trimTags(tag) {
var r = [],
i = 0,
e;
while ((e = tag.firstChild) && e.nodeType === 3 && tTRE[0].test(e.nodeValue))
tag.removeChild(e);
while ((e = tag.lastChild) && e.nodeType === 3 && tTRE[0].test(e.nodeValue))
tag.removeChild(e);
if ((e = tag.firstChild) && e.nodeType === 3)
e.nodeValue = e.nodeValue.replace(tTRE[1], '');
if ((e = tag.lastChild) && e.nodeType === 3)
e.nodeValue = e.nodeValue.replace(tTRE[2], '');
while ((e = tag.firstChild))
r[i++] = tag.removeChild(e);
return r;
}
function randthem(tag) {
var els = oldie ? tag.all : tag.getElementsByTagName('*'),
i = els.length,
childels = [];
while (--i > -1) {
if (els[i].parentNode === tag) {
childels.push(els[i]);
}
}
childels.sort(function() {
return 0.5 - Math.random();
});
i = childels.length;
while (--i > -1) {
tag.appendChild(childels[i]);
}
}
function Marq(c, tag) {
var p, u, s, a, ims, ic, i, marqContent, cObj = this;
this.mq = marqueeInit.ar[c];
if (this.mq.random) {
if (tag.getElementsByTagName && tag.getElementsByTagName('tr').length === 1 && tag.childNodes.length === 1) {
randthem(tag.getElementsByTagName('tr')[0]);
} else {
randthem(tag);
}
}
for (p in defaultconfig)
if ((this.mq.hasOwnProperty && !this.mq.hasOwnProperty(p)) || (!this.mq.hasOwnProperty && !this.mq[p]))
this.mq[p] = defaultconfig[p];
this.mq.style.width = !this.mq.style.width || isNaN(parseInt(this.mq.style.width)) ? '100%' : this.mq.style.width;
if (!tag.getElementsByTagName('img')[0])
this.mq.style.height = !this.mq.style.height || isNaN(parseInt(this.mq.style.height)) ? tag.offsetHeight + 3 + 'px' : this.mq.style.height;
else
this.mq.style.height = !this.mq.style.height || isNaN(parseInt(this.mq.style.height)) ? 'auto' : this.mq.style.height;
u = this.mq.style.width.split(/\d/);
this.cw = this.mq.style.width ? [parseInt(this.mq.style.width), u[u.length - 1]] : ['a'];
marqContent = trimTags(tag);
tag.className = tag.id = '';
tag.removeAttribute('class', 0);
tag.removeAttribute('id', 0);
if (ie)
tag.removeAttribute('className', 0);
tag.appendChild(tag.cloneNode(false));
tag.className = ['marquee', c].join('');
tag.style.overflow = 'hidden';
this.c = tag.firstChild;
this.c.appendChild(this.c.cloneNode(false));
this.c.style.visibility = 'hidden';
a = [
[req1, this.c.style],
[this.mq.style, this.c.style]
];
for (i = a.length - 1; i > -1; --i)
for (p in a[i][0])
if ((a[i][0].hasOwnProperty && a[i][0].hasOwnProperty(p)) || (!a[i][0].hasOwnProperty))
a[i][1][p.encamel()] = a[i][0][p];
this.m = this.c.firstChild;
if (this.mq.mouse === 'pause') {
this.c.onmouseover = function() {
cObj.mq.stopped = true;
};
this.c.onmouseout = function() {
cObj.mq.stopped = false;
};
}
this.m.style.position = 'absolute';
this.m.style.left = '-10000000px';
this.m.style.whiteSpace = 'nowrap';
if (ie5) this.c.firstChild.appendChild((this.m = document.createElement('nobr')));
if (!this.mq.noAddedSpace)
this.m.appendChild(document.createTextNode('\xa0'));
for (i = 0; marqContent[i]; ++i)
this.m.appendChild(marqContent[i]);
if (ie5) this.m = this.c.firstChild;
ims = this.m.getElementsByTagName('img');
if (ims.length) {
for (ic = 0, i = 0; i < ims.length; ++i) {
ims[i].style.display = 'inline';
if (!ims[i].alt && !this.mq.noAddedAlt) {
ims[i].alt = (tTRE[3].exec(ims[i].src)) || ('Image #' + [i + 1]);
if (!ims[i].title) {
ims[i].title = '';
}
}
ims[i].style.display = 'inline';
ims[i].style.verticalAlign = ims[i].style.verticalAlign || 'top';
if (typeof ims[i].complete === 'boolean' && ims[i].complete)
ic++;
else {
ims[i].onload = ims[i].onerror = function() {
if (++ic === ims.length)
cObj.setup(c);
};
}
if (ic === ims.length)
this.setup(c);
}
} else this.setup(c)
}
Marq.prototype.setup = function(c) {
if (this.mq.setup) return;
this.mq.setup = this;
var s, w, cObj = this,
exit = 10000;
if (this.c.style.height === 'auto')
this.c.style.height = this.m.offsetHeight + 4 + 'px';
this.c.appendChild(this.m.cloneNode(true));
this.m = [this.m, this.m.nextSibling];
if (typeof this.mq.initcontent === 'function') {
this.mq.initcontent.apply(this.mq, [this.m]);
}
if (this.mq.mouse === 'cursor driven') {
this.r = this.mq.neutral || 16;
this.sinc = this.mq.inc;
this.c.onmousemove = function(e) {
cObj.mq.stopped = false;
cObj.directspeed(e)
};
if (this.mq.moveatleast) {
this.mq.inc = this.mq.moveatleast;
if (this.mq.savedirection) {
if (this.mq.savedirection === 'reverse') {
this.c.onmouseout = function(e) {
if (cObj.contains(e)) return;
cObj.mq.inc = cObj.mq.moveatleast;
cObj.mq.direction = cObj.mq.direction === 'right' ? 'left' : 'right';
};
} else {
this.mq.savedirection = this.mq.direction;
this.c.onmouseout = function(e) {
if (cObj.contains(e)) return;
cObj.mq.inc = cObj.mq.moveatleast;
cObj.mq.direction = cObj.mq.savedirection;
};
}
} else
this.c.onmouseout = function(e) {
if (!cObj.contains(e)) cObj.mq.inc = cObj.mq.moveatleast;
};
} else
this.c.onmouseout = function(e) {
if (!cObj.contains(e)) cObj.slowdeath();
};
}
this.w = this.m[0].offsetWidth;
this.m[0].style.left = 0;
this.c.id = 'marq_kill_marg_bord';
this.m[0].style.top = this.m[1].style.top = Math.floor((this.c.offsetHeight - this.m[0].offsetHeight) / 2 - oldie) + 'px';
this.c.id = '';
this.c.removeAttribute('id', 0);
this.m[1].style.left = this.w + 'px';
s = this.mq.moveatleast ? Math.max(this.mq.moveatleast, this.sinc) : (this.sinc || this.mq.inc);
while (this.c.offsetWidth > this.w - s && --exit) {
w = isNaN(this.cw[0]) ? this.w - s : --this.cw[0];
if (w < 1 || this.w < Math.max(1, s)) {
break;
}
this.c.style.width = isNaN(this.cw[0]) ? this.w - s + 'px' : --this.cw[0] + this.cw[1];
}
this.c.style.visibility = 'visible';
this.runit();
}
Marq.prototype.slowdeath = function() {
var cObj = this;
if (this.mq.inc) {
this.mq.inc -= 1;
this.timer = setTimeout(function() {
cObj.slowdeath();
}, 100);
}
}
Marq.prototype.runit = function() {
var cObj = this,
d = this.mq.direction === 'right' ? 1 : -1;
if (this.mq.stopped || this.mq.stopMarquee) {
setTimeout(function() {
cObj.runit();
}, 300);
return;
}
if (this.mq.mouse != 'cursor driven')
this.mq.inc = Math.max(1, this.mq.inc);
if (d * parseInt(this.m[0].style.left) >= this.w)
this.m[0].style.left = parseInt(this.m[1].style.left) - d * this.w + 'px';
if (d * parseInt(this.m[1].style.left) >= this.w)
this.m[1].style.left = parseInt(this.m[0].style.left) - d * this.w + 'px';
this.m[0].style.left = parseInt(this.m[0].style.left) + d * this.mq.inc + 'px';
this.m[1].style.left = parseInt(this.m[1].style.left) + d * this.mq.inc + 'px';
setTimeout(function() {
cObj.runit();
}, 30 + (this.mq.addDelay || 0));
}
Marq.prototype.directspeed = function(e) {
e = e || window.event;
if (this.timer) clearTimeout(this.timer);
var c = this.c,
w = c.offsetWidth,
l = c.offsetLeft,
mp = (typeof e.pageX === 'number' ?
e.pageX : e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft) - l,
lb = (w - this.r) / 2,
rb = (w + this.r) / 2;
while ((c = c.offsetParent)) mp -= c.offsetLeft;
this.mq.direction = mp > rb ? 'left' : 'right';
this.mq.inc = Math.round((mp > rb ? (mp - rb) : mp < lb ? (lb - mp) : 0) / lb * this.sinc);
}
Marq.prototype.contains = function(e) {
if (e && e.relatedTarget) {
var c = e.relatedTarget;
if (c === this.c) return true;
while ((c = c.parentNode))
if (c === this.c) return true;
}
return false;
}
function resize() {
for (var s, w, m, i = 0; i < marqueeInit.ar.length; ++i) {
if (marqueeInit.ar[i] && marqueeInit.ar[i].setup) {
m = marqueeInit.ar[i].setup;
s = m.mq.moveatleast ? Math.max(m.mq.moveatleast, m.sinc) : (m.sinc || m.mq.inc);
m.c.style.width = m.mq.style.width;
m.cw[0] = m.cw.length > 1 ? parseInt(m.mq.style.width) : 'a';
while (m.c.offsetWidth > m.w - s) {
w = isNaN(m.cw[0]) ? m.w - s : --m.cw[0];
if (w < 1) {
break;
}
m.c.style.width = isNaN(m.cw[0]) ? m.w - s + 'px' : --m.cw[0] + m.cw[1];
}
}
}
}
function unload() {
for (var m, i = 0; i < marqueeInit.ar.length; ++i) {
if (marqueeInit.ar[i] && marqueeInit.ar[i].persist && marqueeInit.ar[i].setup) {
m = marqueeInit.ar[i].setup;
m.cookie.set(m.mq.uniqueid, m.m[0].style.left + ':' + m.m[1].style.left + ':' + m.mq.direction);
}
}
}
if (window.addEventListener) {
window.addEventListener('resize', resize, false);
window.addEventListener('unload', unload, false);
} else if (window.attachEvent) {
window.attachEvent('onresize', resize);
window.attachEvent('onunload', unload);
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="marquee" id="mycrawler">
Those confounded friars dully buzz that faltering jay. An appraising tongue acutely causes our courageous hogs. Their fitting submarines deftly break your approving improvisations. Her downcast taxonomies actually box up those disgusted turtles.
</div>
I have one function for the number input box come with + and - button on the sides, and copy the code in my shopify theme which I use. But that function only show one time. But I need those apply to all the product offers.
(function ($) {
$.fn.bootstrapNumber = function (options) {
var settings = $.extend({
upClass: 'default',
downClass: 'default',
center: true
}, options);
return this.each(function (e) {
var self = $(this);
var clone = self.clone();
var min = self.attr('min');
var max = self.attr('max');
function setText(n) {
if ((min && n < min) || (max && n > max)) {
return false;
}
clone.focus().val(n);
return true;
}
var group = $("<div class='input-group'></div>");
var down = $("<button type='button'>-</button>").attr('class', 'btn btn-' + settings.downClass).click(function () {
setText(parseInt(clone.val()) - 1);
});
var up = $("<button type='button'>+</button>").attr('class', 'btn btn-' + settings.upClass).click(function () {
setText(parseInt(clone.val()) + 1);
});
$("<span class='input-group-btn'></span>").append(down).appendTo(group);
clone.appendTo(group);
if (clone) {
clone.css('text-align', 'center');
}
$("<span class='input-group-btn'></span>").append(up).appendTo(group);
// remove spins from original
clone.prop('type', 'text').keydown(function (e) {
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
(e.keyCode == 65 && e.ctrlKey === true) ||
(e.keyCode >= 35 && e.keyCode <= 39)) {
return;
}
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
var c = String.fromCharCode(e.which);
var n = parseInt(clone.val() + c);
//if ((min && n < min) || (max && n > max)) {
// e.preventDefault();
//}
});
clone.prop('type', 'text').blur(function (e) {
var c = String.fromCharCode(e.which);
var n = parseInt(clone.val() + c);
if ((min && n < min)) {
setText(min);
}
else if (max && n > max) {
setText(max);
}
});
self.replaceWith(group);
});
};
}(jQuery));
How do you initialise the function ?
Your problem certainly lies there...
Because it works using this:
$('input').bootstrapNumber();
See my Fiddle that includes your exact unmodified script.
Is there available binding to format an input value from 123456789 to 123,456,789. The binding should work on every keypress and validate the value if it is a valid number. I found this solution but it is not formatting on keypress.
I ended up creating custom binding. It only works on IE10 and above for the usage of event input.
Here's the code. See fiddle here.
String.prototype.countOccurence = function(char){
return (this).split(char).length - 1;
}
$.fn.selectRange = function(start, end){
if(end === undefined)
end = start;
return this.each(function() {
if("selectionStart" in this){
this.selectionStart = start;
this.selectionEnd = end;
} else if(this.setSelectionRange)
this.setSelectionRange(start, end);
else if(this.createTextRange){
var range = this.createTextRange();
range.collapse(true);
range.moveEnd("character", end);
range.moveStart("character", start);
range.select();
}
});
};
ko.helper = {};
ko.helper['toNumber'] = function (value, limit){
limit = limit || 10;
var num = Number((value || "").toString().replace(/[^0-9]/gi, "").substring(0, limit));
return num;
}
ko.bindingHandlers['formatNumber'] = {
init: function(element, valueAccessor, allBindings){
var value = valueAccessor();
var limit = allBindings.get("limit") || 10; //billion
var position = 0;
var navigationKeys = [33, 34, 35, 36, 37, 38, 39, 40, 9];
var isBackSpace = false;
var oldLengthValue = (value() || "").toString().length;
function isKeyControls(e){
if(e.ctrlKey && (e.keyCode == 67 || e.keyCode == 86 || e.keyCode == 65)){
return true;
}
if(e.shiftKey && (e.keyCode == 37 || e.keyCode == 39)){
return true;
}
return false;
}
$(element).on("keyup", function(e) {
if(this.selectionStart == this.value.length)
return;
if(isKeyControls(e) || e.shiftKey){
return;
}
var navigation = (e.keyCode == 37
? -1
: e.keyCode == 39
? 1
: 0);
var customSelectionStart = this.selectionStart; // + navigation;
//customSelectionStart = customSelectionStart
var positionMinusOne = customSelectionStart == 0
? -1
: customSelectionStart;
positionMinusOne = positionMinusOne + (positionMinusOne == -1 ? 0 : navigation);
var previousCharacter = positionMinusOne == -1
? ""
: this.value.substring(customSelectionStart - 1, customSelectionStart);
if(previousCharacter == ","){
$(this).selectRange(customSelectionStart +
(isBackSpace ? -1 : 0));
}
var currentCommaOccurence = this.value.countOccurence(",");
var commaValue = oldLengthValue > currentCommaOccurence ? -1
: oldLengthValue < currentCommaOccurence ? 1
: 0;
if(commaValue != 0){
$(this).selectRange(customSelectionStart +
commaValue);
}
oldLengthValue = this.value.countOccurence(",");
});
$(element).on("keydown", function (e) {
if (isKeyControls(e)) {
return;
}
var navigation = (e.keyCode == 37
? -1
: e.keyCode == 39
? 1
: 0);
var customSelectionStart = this.selectionStart + navigation;
//customSelectionStart = customSelectionStart
var positionMinusOne = customSelectionStart == 0
? -1
: customSelectionStart;
positionMinusOne = positionMinusOne + (positionMinusOne == -1 ? 0 : navigation);
var previousCharacter = positionMinusOne == -1
? ""
: this.value.substring(customSelectionStart - 1, customSelectionStart);
if(previousCharacter == ",")
$(this).selectRange(customSelectionStart);
isBackSpace = e.keyCode == 8;
if(isBackSpace)
return;
//Navigation
if(navigationKeys.some(function(key) {
return key == e.keyCode;
}))
return;
//Other Keys
var isNumber = (e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105);
var isLimit = (limit + parseInt(limit / 3)) == this.value.length;
if(!(isNumber)
|| isLimit){
e.preventDefault();
return;
}
});
$(element).on("input", function(e, a, b, c) {
console.log(this.selectionStart, this.selectionEnd);
var convertedValue = ko.helper.toNumber(this.value, limit);
var formatted = convertedValue
? ko.helper.toNumber(this.value, limit).toLocaleString()
: "";
position = this.selectionStart == this.value.length
? formatted.length
: this.selectionStart;
value(convertedValue || "");
this.value = formatted;
$(this).selectRange(position);
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).off();
});
ko.bindingHandlers["formatNumber"].update(element, valueAccessor, allBindings);
},
update: function(element, valueAccessor, allBindings){
var value = valueAccessor();
var limit = allBindings.get("limit") || 10; //billion
var convertedValue = ko.helper.toNumber(value(), limit);
var formatted = convertedValue
? ko.helper.toNumber(value(), limit).toLocaleString()
: "";
element.value = formatted;
}
};