Javascript Image Slider - How to keep moving on mouse hover - javascript

I found a javascript image slider here: https://codepen.io/EricPorter/pen/XaOEpP and wanted to use it for my project.
I narrowed down the script to what I wanted below. It's exactly what I am looking to do except one thing. It pauses on mouse hover.
I have tried a few different things, but I cannot figure out how to keep the script sliding on mouse hover. I am somewhat limited in JS, I typically use vendor scripts and adjust as needed, if you could give a solution and explain the piece that is pausing it on mouse hover, I would greatly appreciate it.
Thank you in advance!
! function(o) {
"use strict";
o.fn.sliderResponsive = function(i) {
var n, e = o.extend({
slidePause: 4e3,
fadeSpeed: 600,
autoPlay: "on",
showArrows: "on",
hideDots: "on",
hoverZoom: "off",
titleBarTop: "off"
}, i),
d = o(this),
s = d.find("> div").length,
t = 0;
function f() {
n = setInterval(function() {
l()
}, e.slidePause)
}
function l() {
(t = d.find(".show").index() + 1) > s - 1 && (t = 0), a()
}
function a() {
d.find(".show").removeClass("show").fadeOut(), d.find("> div").eq(t).fadeIn(e.fadeSpeed).addClass("show"), d.find("> ul").find(".showli").removeClass("showli"), d.find("> ul > li").eq(t).addClass("showli")
}
return d.append("<ul></ul>"), d.find("> div").each(function() {
d.find("> ul").append("<li></li>")
}), d.find("div:first-of-type").addClass("show"), d.find("li:first-of-type").addClass("showli"), d.find("> div").not(".show").fadeOut(), "on" === e.autoPlay && f(), "on" === e.showArrows && d.addClass("showArrows"), "on" === e.hideDots && d.addClass("hideDots"), "off" === e.hoverZoom && d.addClass("hoverZoomOff"), "on" === e.titleBarTop && d.addClass("titleBarTop"), d.mouseover(function() {
"on" === e.autoPlay && clearInterval(n)
}), d.mouseout(function() {
"on" === e.autoPlay && f()
}), d.find("> .right").click(l), d.find("> .left").click(function() {
(t = d.find(".show").index() - 1) < 0 && (t = s - 1);
a()
}), d.find(" > ul > li").click(function() {
t = o(this).index(), a(o(this).index())
}), d
}
}(jQuery), $(document).ready(function() {
$("#slider3").sliderResponsive({
hoverZoom: "on"
})
});

You can add a new property to the settings object like below and then check for if the new property is set to on or off in the onmouseover and onmouseout functions.
Note: check the three comments in the code below
! function(o) {
"use strict";
o.fn.sliderResponsive = function(i) {
var n, e = o.extend({
slidePause: 4e3,
fadeSpeed: 600,
autoPlay: "on",
showArrows: "on",
hideDots: "on",
hoverZoom: "off",
titleBarTop: "off",
hoverStopPlay: "off" // <-- Add new property
}, i),
d = o(this),
s = d.find("> div").length,
t = 0;
function f() {
n = setInterval(function() {
l()
}, e.slidePause)
}
function l() {
(t = d.find(".show").index() + 1) > s - 1 && (t = 0), a()
}
function a() {
d.find(".show").removeClass("show").fadeOut(), d.find("> div").eq(t).fadeIn(e.fadeSpeed).addClass("show"), d.find("> ul").find(".showli").removeClass("showli"), d.find("> ul > li").eq(t).addClass("showli")
}
return d.append("<ul></ul>"), d.find("> div").each(function() {
d.find("> ul").append("<li></li>")
}), d.find("div:first-of-type").addClass("show"), d.find("li:first-of-type").addClass("showli"), d.find("> div").not(".show").fadeOut(), "on" === e.autoPlay && f(), "on" === e.showArrows && d.addClass("showArrows"), "on" === e.hideDots && d.addClass("hideDots"), "off" === e.hoverZoom && d.addClass("hoverZoomOff"), "on" === e.titleBarTop && d.addClass("titleBarTop"), d.mouseover(function() {
if("on" === e.autoPlay && e.hoverStopPlay === "on") { // <-- Add new condition
clearInterval(n);
}
}), d.mouseout(function() {
if("on" === e.autoPlay && e.hoverStopPlay === "on") { // <-- Add new condition
f();
}
}), d.find("> .right").click(l), d.find("> .left").click(function() {
(t = d.find(".show").index() - 1) < 0 && (t = s - 1);
a()
}), d.find(" > ul > li").click(function() {
t = o(this).index(), a(o(this).index())
}), d
}
}(jQuery), $(document).ready(function() {
$("#slider3").sliderResponsive({
hoverZoom: "on"
})
});

Related

Block inline script detecting devtools on edge/chromium

I am running the chromium version of edge, and have installed ublock origin, and I just wondering how I could disable this script from being loaded on a site. either through overrides or ublock origin preferably
<script data-cfasync="false" type="text/javascript">
if (-1 != navigator.userAgent.indexOf("Chrome") || -1 != navigator.userAgent.indexOf("Safari") || -1 != navigator.userAgent.indexOf("MSIE") || -1 != navigator.userAgent.indexOf("coc_coc_browser")) {
var checkStatus, element = new Image;
Object.defineProperty(element, "id", {
get: function() {
throw checkStatus = "on", new Error("Dev tools checker")
}
}), setInterval(function() {
checkStatus = "off", console.dir(element), "on" == checkStatus && (-1 != window.location.href.indexOf("?ep=")) && (window.location.href = window.location.href.split("watching.html")[0])
}, 1e3)
} - 1 != navigator.userAgent.indexOf("Firefox") && window.addEventListener("devtoolschange", e => {
1 == e.detail.isOpen && (-1 != window.location.href.indexOf("?ep=")) && (window.location.href = window.location.href.split("watching.html")[0])
});
! function() {
"use strict";
const i = {
isOpen: !1,
orientation: void 0
},
e = (i, e) => {
window.dispatchEvent(new CustomEvent("devtoolschange", {
detail: {
isOpen: i,
orientation: e
}
}))
};
setInterval(() => {
const n = window.outerWidth - window.innerWidth > 160,
o = window.outerHeight - window.innerHeight > 160,
t = n ? "vertical" : "horizontal";
o && n || !(window.Firebug && window.Firebug.chrome && window.Firebug.chrome.isInitialized || n || o) ? (i.isOpen && e(!1, void 0), i.isOpen = !1, i.orientation = void 0) : (i.isOpen && i.orientation === t || e(!0, t), i.isOpen = !0, i.orientation = t)
}, 500), "undefined" != typeof module && module.exports ? module.exports = i : window.devtools = i
}();
window.addEventListener("devtoolschange", e => {
e.detail.isOpen && (-1 != window.location.href.indexOf("?ep=")) && (window.location.href = window.location.href.split("watching.html")[0])
});
</script>
If it is a separate js file, you can block specific js files to load. Open DevTools -> network tab -> select file and right click -> choose block Request URL.
But if it is loaded on the page, I think this will not be possible. If you choose to disable javascript, then all the script content of the page will not work, which will affect the overall operation of the page.
uBO has some nice tools to stop these.
Have a look at https://github.com/uBlockOrigin/uBlock-issues/wiki/Resources-Library

How are pointers referenced in JS?

I found this code while doing a random task, and I'm wondering how it works with the memory in JS.
There are obviously more that one level of nested functions, which reference variables from all sorts of levels above (outer contexts). Specifically the variable i.
!function () {
function valOrDef(val, def) {
var _val, _def = typeof def === 'undefined' ? 0 : def;
if (typeof val !== 'undefined' && typeof val !== null) _val = parseFloat(val, 10);
return !isNaN(_val) ? _val : _def;
}
function reg(els,l) {
if (!els || !(l = els.length)) return;
function h(el) {
var p = el.querySelector('button.decrease'),
i = el.querySelector('input'),
n = el.querySelector('button.increase');
var min = valOrDef(i.min, 0), step = valOrDef(i.step, 1);
function inc(e) { e.preventDefault(); e.stopPropagation(); i.value = Math.max(min, valOrDef(i.value, 0) + step); fire(); }
function dec(e) { e.preventDefault(); e.stopPropagation(); i.value = Math.max(min, valOrDef(i.value, 0) - step); fire(); }
function chk() { i.value = valOrDef(i.value, min); }
function fire() { i.dispatchEvent(new Event('change')); }
p.addEventListener('pointerup', dec, true);
n.addEventListener('pointerup', inc, true);
i.addEventListener('change', chk, false);
}
while (l--) h(els[l]);
}
reg(document.querySelectorAll('.single-inc-dec'));
}();
So, I'm wondering, is that a wasting memory, because each callback has it's own "environment" with it's own pointers?
I think it will be more efficent to have the methods in an outer scope, and provide them with arguments. In this case the inc, dec & fire outside the reg function, and recieve the i as a parameter. So something like this:
!function () {
function valOrDef(val, def) {
var _val, _def = typeof def === 'undefined' ? 0 : def;
if (typeof val !== 'undefined' && typeof val !== null) _val = parseFloat(val, 10);
return !isNaN(_val) ? _val : _def;
}
function inc(i) { return function(e) { e.preventDefault(); e.stopPropagation(); i.value = Math.max(min, valOrDef(i.value, 0) + step); fire(i); } }
function dec(i) { return function(e) { e.preventDefault(); e.stopPropagation(); i.value = Math.max(min, valOrDef(i.value, 0) - step); fire(); }
function fire(i) { i.dispatchEvent(new Event('change')); }
function reg(els,l) {
if (!els || !(l = els.length)) return;
function h(el) {
var p = el.querySelector('button.decrease'),
i = el.querySelector('input'),
n = el.querySelector('button.increase');
var min = valOrDef(i.min, 0), step = valOrDef(i.step, 1);
function chk() { i.value = valOrDef(i.value, min); }
p.addEventListener('pointerup', dec(i), true);
n.addEventListener('pointerup', inc(i), true);
i.addEventListener('change', chk, false);
}
while (l--) h(els[l]);
}
reg(document.querySelectorAll('.single-inc-dec'));
}();
I know that this code will still produce a callback-function for each instance of the listeners, just wondering about the mechanics behind this.
Any pointers to what keywords I should be lookign for to read up on this are also welcomed. :)
Please don't crusify me over this code. It's not mine. I was just told "The buttons are slow on the iPhone. Fix that", while doing that I found this gem.

How to circumvent a "blockadblock" script with a benign adblock friendly substitute?

A website I interact with employs the following adblock detection script (beautified for readability):
! function(t) {
var e = function(e) {
this._options = {
checkOnLoad: !1,
resetOnEnd: !1,
loopCheckTime: 50,
loopMaxNumber: 5,
baitClass: "pub_300x250 pub_300x250m pub_728x90 text-ad textAd text_ad text_ads text-ads text-ad-links",
baitStyle: "width: 1px !important; height: 1px !important; position: absolute !important; left: -10000px !important; top: -1000px !important;",
debug: !1
}, this._var = {
version: "3.2.1",
bait: null,
checking: !1,
loop: null,
loopNumber: 0,
event: {
detected: [],
notDetected: []
}
}, void 0 !== e && this.setOption(e);
var o = this,
i = function() {
setTimeout(function() {
o._options.checkOnLoad === !0 && (o._options.debug === !0 && o._log("onload->eventCallback", "A check loading is launched"), null === o._var.bait && o._creatBait(), setTimeout(function() {
o.check()
}, 1))
}, 1)
};
void 0 !== t.addEventListener ? t.addEventListener("load", i, !1) : t.attachEvent("onload", i)
};
e.prototype._options = null, e.prototype._var = null, e.prototype._bait = null, e.prototype._log = function(t, e) {
console.log("[BlockAdBlock][" + t + "] " + e)
}, e.prototype.setOption = function(t, e) {
if (void 0 !== e) {
var o = t;
t = {}, t[o] = e
}
for (var i in t) this._options[i] = t[i], this._options.debug === !0 && this._log("setOption", 'The option "' + i + '" he was assigned to "' + t[i] + '"');
return this
}, e.prototype._creatBait = function() {
var e = document.createElement("div");
e.setAttribute("class", this._options.baitClass), e.setAttribute("style", this._options.baitStyle), this._var.bait = t.document.body.appendChild(e), this._var.bait.offsetParent, this._var.bait.offsetHeight, this._var.bait.offsetLeft, this._var.bait.offsetTop, this._var.bait.offsetWidth, this._var.bait.clientHeight, this._var.bait.clientWidth, this._options.debug === !0 && this._log("_creatBait", "Bait has been created")
}, e.prototype._destroyBait = function() {
t.document.body.removeChild(this._var.bait), this._var.bait = null, this._options.debug === !0 && this._log("_destroyBait", "Bait has been removed")
}, e.prototype.check = function(t) {
if (void 0 === t && (t = !0), this._options.debug === !0 && this._log("check", "An audit was requested " + (t === !0 ? "with a" : "without") + " loop"), this._var.checking === !0) return this._options.debug === !0 && this._log("check", "A check was canceled because there is already an ongoing"), !1;
this._var.checking = !0, null === this._var.bait && this._creatBait();
var e = this;
return this._var.loopNumber = 0, t === !0 && (this._var.loop = setInterval(function() {
e._checkBait(t)
}, this._options.loopCheckTime)), setTimeout(function() {
e._checkBait(t)
}, 1), this._options.debug === !0 && this._log("check", "A check is in progress ..."), !0
}, e.prototype._checkBait = function(e) {
var o = !1;
if (null === this._var.bait && this._creatBait(), (null !== t.document.body.getAttribute("abp") || null === this._var.bait.offsetParent || 0 == this._var.bait.offsetHeight || 0 == this._var.bait.offsetLeft || 0 == this._var.bait.offsetTop || 0 == this._var.bait.offsetWidth || 0 == this._var.bait.clientHeight || 0 == this._var.bait.clientWidth) && (o = !0), void 0 !== t.getComputedStyle) {
var i = t.getComputedStyle(this._var.bait, null);
!i || "none" != i.getPropertyValue("display") && "hidden" != i.getPropertyValue("visibility") || (o = !0)
}
this._options.debug === !0 && this._log("_checkBait", "A check (" + (this._var.loopNumber + 1) + "/" + this._options.loopMaxNumber + " ~" + (1 + this._var.loopNumber * this._options.loopCheckTime) + "ms) was conducted and detection is " + (o === !0 ? "positive" : "negative")), e === !0 && (this._var.loopNumber++, this._var.loopNumber >= this._options.loopMaxNumber && this._stopLoop()), o === !0 ? (this._stopLoop(), this._destroyBait(), this.emitEvent(!0), e === !0 && (this._var.checking = !1)) : (null === this._var.loop || e === !1) && (this._destroyBait(), this.emitEvent(!1), e === !0 && (this._var.checking = !1))
}, e.prototype._stopLoop = function(t) {
clearInterval(this._var.loop), this._var.loop = null, this._var.loopNumber = 0, this._options.debug === !0 && this._log("_stopLoop", "A loop has been stopped")
}, e.prototype.emitEvent = function(t) {
this._options.debug === !0 && this._log("emitEvent", "An event with a " + (t === !0 ? "positive" : "negative") + " detection was called");
var e = this._var.event[t === !0 ? "detected" : "notDetected"];
for (var o in e) this._options.debug === !0 && this._log("emitEvent", "Call function " + (parseInt(o) + 1) + "/" + e.length), e.hasOwnProperty(o) && e[o]();
return this._options.resetOnEnd === !0 && this.clearEvent(), this
}, e.prototype.clearEvent = function() {
this._var.event.detected = [], this._var.event.notDetected = [], this._options.debug === !0 && this._log("clearEvent", "The event list has been cleared")
}, e.prototype.on = function(t, e) {
return this._var.event[t === !0 ? "detected" : "notDetected"].push(e), this._options.debug === !0 && this._log("on", 'A type of event "' + (t === !0 ? "detected" : "notDetected") + '" was added'), this
}, e.prototype.onDetected = function(t) {
return this.on(!0, t)
}, e.prototype.onNotDetected = function(t) {
return this.on(!1, t)
}, t.BlockAdBlock = e, void 0 === t.blockAdBlock && (t.blockAdBlock = new e({
checkOnLoad: !0,
resetOnEnd: !0
}))
}(window);
The site design is such that this script cannot be blocked without halting the functionality of the site. I haven't consented to any EULA with this site and I believe I'm well within my rights to tamper with my client side code. I simply wish to circumvent this script with a benign adblock friendly substitute.
Essentially, I'd like to inject a user-defined script that will simulate the adblock notification event and give the server the impression that I have clicked through the following popup notification:
The approach I'd like try for this problem was suggested by #jake-holzinger. He remarked the script might be subverted by forcing the e class prototype to trigger the opposite adblock detection code, i.e. by overwritting e.prototype.onDetected with e.prototype.onNotDetected; although, I assume the same effect can be achieved by flipping the Boolean? As he explains it, this subverted code should be executed prior to the load event, but only after the above default code is run (I could be misinterpreting this part).
As a novice with JavaScript, I find these instructions a bit terse and opaque. In particular, I'm not entirely sure what the control flow is supposed to look like here. It seems like the default blockadblock script should be run (not blocked or replaced), but for some reason this needs to take place before the subverted code? Is the "subverted code" in this case a perfect replica of the blockadblock script, with the only difference being the inverted event names; or Boolean? What does it mean for the subverted code to be run before the load event? Isn't this already the case? Or do I need restructure the code to achieve this effect?

Javascript code not working in Visual Studio Express 2013 Preview for Windows

So, This is my first Windows 8 app and I'm working on it using html/css and JS
I've developped it on a browser at first (I know, not a good habit) and I wanted to try it out on the Windows 8.1 app
Everything seemed to have slight glitches that I easily fixed, yet the javascript code didn't work at all, even though it worked perfectly on the browser.
Short story: the app enables you to make a countdown from 1h down, or 10mn down (for some purpose), it has two bottuns for each countdown: a start and a stop button.
I have no idea why, the cosole shows the following error: HTML1701
Here's the code:
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// TODO: This application has been newly launched. Initialize
// your application here.
} else {
// TODO: This application has been reactivated from suspension.
// Restore application state here.
}
args.setPromise(WinJS.UI.processAll());
}
};
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state
// that needs to persist across suspensions here. You might use the
// WinJS.Application.sessionState object, which is automatically
// saved and restored across suspension. If you need to complete an
// asynchronous operation before your application is suspended, call
// args.setPromise().
$(document).ready(function () {
var h, m, s, h1, m1, s1, output, output1, inter, inter1;
//Preparing all the functions
//facts' animation function
function facts() {
function solve() {
setTimeout(function () {
$("#fun1").animate({ opacity: "0", }, 500, function () {
$("#fun2").animate({ opacity: "1" }, 500);
});
}, 10500);
setTimeout(function () {
$("#fun2").animate({ opacity: "0", }, 500, function () {
$("#fun3").animate({ opacity: "1" }, 500);
});
}, 21500);
setTimeout(function () {
$("#fun3").animate({ opacity: "0", }, 500, function () {
$("#fun4").animate({ opacity: "1" }, 500);
});
}, 31500);
setTimeout(function () {
$("#fun4").animate({ opacity: "0", }, 500, function () {
$("#fun1").animate({ opacity: "1" }, 500);
});
}, 41500);
}
solve();
setInterval(function () { solve(); }, 41520);
//Work Counting functions
}
function startWork() {
h = 1;
m = 0;
s = 0;
document.getElementById("WTM").innerHTML = "01:00:00"
inter = setInterval(function () { countWork() }, 1000);
}
function countWork() {
if (s == 0 && m == 0 && h == 0) {
$("#StartW").animate({ opacity: 1, }, 500);
clearInterval(inter);
}
else if (s == 0 && m == 0 && h != 0) {
h = h - 1;
m = 59;
s = 59;
}
else if (s == 0 && m != 0) {
m = m - 1;
s = 59;
}
else if (s != 0)
{ s = s - 1; }
if (typeof (s) != "string" && s < 10)
{ s = "0" + s; }
if (typeof (m) != "string" && m < 10)
{ m = "0" + m; }
if (typeof (h) != "string" && h < 10)
{ h = "0" + h; }
output = h + ":" + m + ":" + s;
document.getElementById("WTM").innerHTML = output;
}
//Rest Counting functions
function startRest() {
h1 = 0;
m1 = 10;
s1 = 0;
document.getElementById("RTM").innerHTML = "00:10:00";
inter1 = setInterval(function () { countRest() }, 1000);
}
function countRest() {
if (s1 == 0 && m1 == 0 && h1 == 0) {
$("#StartR").animate({ opacity: 1, }, 500);
clearInterval(inter1);
}
else if (s1 == 0 && m1 == 0 && h1 != 0) {
h1 = h1 - 1;
m1 = 59;
s1 = 59;
}
else if (s1 == 0 && m1 != 0) {
m1 = m1 - 1;
s1 = 59;
}
else if (s1 != 0)
{ s1 = s1 - 1; }
if (typeof (s1) != "string" && s1 < 10)
{ s1 = "0" + s1; }
if (typeof (m1) != "string" && m1 < 10)
{ m1 = "0" + m1; }
if (typeof (h1) != "string" && h1 < 10)
{ h1 = "0" + h1; }
output1 = h1 + ":" + m1 + ":" + s1;
document.getElementById("RTM").innerHTML = output1;
}
//Calling the needed functions
$("#StopW").click(function () {
clearInterval(inter);
document.getElementById("WTM").innerHTML = "00:00:00";
$("#StartW").animate({ opacity: 1, }, 500);
});
$("#StartW").click(function () {
startWork();
$("#StartW").animate({ opacity: 0, }, 2000);
});
$("#StopR").click(function () {
clearInterval(inter1);
document.getElementById("RTM").innerHTML = "00:00:00";
$("#StartR").animate({ opacity: 1, }, 500);
});
$("#StartR").click(function () {
startRest();
$("#StartR").animate({ opacity: 0, }, 2000);
});
facts();
});
};
app.start();
})();
It appears you're using jQuery. Make sure you're using jQuery 2.0 and serving it locally from your app package.
The specific error you're seeing is likely the result of using innerHTML to set the countdown timers. Because apps run with elevated privileges (potential access to user files, etc), your code must not do things that may introduce vulnerabilities. innerHTML can be used to dynamically load scripts and thus it's use is discouraged.
In your application it looks like you could easily use innerText instead. If you must use innerHTML, try using toStaticHTML() or wrapping it in MSApp.execUnsafeLocalFunction(). You can read more about developing secure apps.
don't use the VS2013 Previews any longer. The RTM is already out. Get the final Version here:
http://www.microsoft.com/visualstudio/eng/downloads#d-2013-express

Calling a javascript function for a particular class for a particular spinner button

I have following ui-spinner.js file, developed by some UI Developer:
(function($, undefined) {
var
// constants
active = 'ui-state-active',
hover = 'ui-state-hover',
disabled = 'ui-state-disabled',
keyCode = $.ui.keyCode,
up = keyCode.UP,
down = keyCode.DOWN,
right = keyCode.RIGHT,
left = keyCode.LEFT,
pageUp = keyCode.PAGE_UP,
pageDown = keyCode.PAGE_DOWN,
home = keyCode.HOME,
end = keyCode.END,
msie = $.browser.msie,
mouseWheelEventName = $.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel',
// namespace for events on input
eventNamespace = '.uispinner',
// only these special keys will be accepted, all others will be ignored unless CTRL or ALT are pressed
validKeys = [up, down, right, left, pageUp, pageDown, home, end, keyCode.BACKSPACE, keyCode.DELETE, keyCode.TAB],
// stores the currently focused spinner
// Note: due to oddities in the focus/blur events, this is part of a two-part system for confirming focus
// this must set to the control, and the focus variable must be true
// this is because hitting up/down arrows with mouse causes focus to change, but blur event for previous control doesn't fire
focusCtrl;
$.widget('ui.spinner', {
options: {
min: null,
max: null,
allowNull: false,
group: '',
point: '.',
prefix: '',
suffix: '',
places: null, // null causes it to detect the number of places in step
defaultStep: 1, // real value is 'step', and should be passed as such. This value is used to detect if passed value should override HTML5 attribute
largeStep: 10,
mouseWheel: true,
increment: 'slow',
className: null,
showOn: 'always',
width: 16,
upIconClass: "ui-icon-triangle-1-n",
downIconClass: "ui-icon-triangle-1-s",
format: function(num, places) {
var options = this,
regex = /(\d+)(\d{3})/,
result = ((isNaN(num) ? 0 : Math.abs(num)).toFixed(places)) + '';
for (result = result.replace('.', options.point); regex.test(result) && options.group; result=result.replace(regex, '$1'+options.group+'$2')) {};
return (num < 0 ? '-' : '') + options.prefix + result + options.suffix;
},
parse: function(val) {
var options = this;
if (options.group == '.')
val = val.replace('.', '');
if (options.point != '.')
val = val.replace(options.point, '.');
return parseFloat(val.replace(/[^0-9\-\.]/g, ''));
}
},
// * Widget fields *
// curvalue - current value
// places - currently effective number of decimal places
// oWidth - original input width (used for destroy)
// oMargin - original input right margin (used for destroy)
// counter - number of spins at the current spin speed
// incCounter - index within options.increment of the current spin speed
// selfChange - indicates that change event is being fired by the widget, so don't reprocess input value
// inputMaxLength - initial maxLength value on the input
// focused - this spinner currently has the focus
_create: function() {
// shortcuts
var self = this,
input = self.element,
type = input.attr('type');
if (!input.is('input') || ((type != 'text') && (type != 'number'))) {
console.error('Invalid target for ui.spinner');
return;
}
self._procOptions(true);
self._createButtons(input);
if (!input.is(':enabled'))
self.disable();
},
_createButtons: function(input) {
function getMargin(margin) {
// IE8 returns auto if no margin specified
return margin == 'auto' ? 0 : parseInt(margin);
}
var self = this,
options = self.options,
className = options.className,
buttonWidth = options.width,
showOn = options.showOn,
box = $.support.boxModel,
height = input.outerHeight(),
rightMargin = self.oMargin = getMargin(input.css('margin-right')), // store original width and right margin for later destroy
wrapper = self.wrapper = input.css({ width: (self.oWidth = (box ? input.width() : input.outerWidth())) - buttonWidth,
marginRight: rightMargin + buttonWidth, textAlign: 'right' })
.after('<span class="ui-spinner ui-widget"></span>').next(),
btnContainer = self.btnContainer = $(
'<div class="ui-spinner-buttons">' +
'<div class="ui-spinner-up ui-spinner-button ui-state-default ui-corner-tr"><span class="ui-icon '+options.upIconClass+'"> </span></div>' +
'<div class="ui-spinner-down ui-spinner-button ui-state-default ui-corner-br"><span class="ui-icon '+options.downIconClass+'"> </span></div>' +
'</div>'),
// object shortcuts
upButton, downButton, buttons, icons,
hoverDelay,
hoverDelayCallback,
// current state booleans
hovered, inKeyDown, inSpecialKey, inMouseDown,
// used to reverse left/right key directions
rtl = input[0].dir == 'rtl';
// apply className before doing any calculations because it could affect them
if (className) wrapper.addClass(className);
wrapper.append(btnContainer.css({ height: height, left: -buttonWidth-rightMargin,
// use offset calculation to fix vertical position in Firefox
top: (input.offset().top - wrapper.offset().top) + 'px' }));
buttons = self.buttons = btnContainer.find('.ui-spinner-button');
buttons.css({ width: buttonWidth - (box ? buttons.outerWidth() - buttons.width() : 0), height: height/2 - (box ? buttons.outerHeight() - buttons.height() : 0) });
upButton = buttons[0];
downButton = buttons[1];
// fix icon centering
icons = buttons.find('.ui-icon');
icons.css({ marginLeft: (buttons.innerWidth() - icons.width()) / 2, marginTop: (buttons.innerHeight() - icons.height()) / 2 });
// set width of btnContainer to be the same as the buttons
btnContainer.width(buttons.outerWidth());
if (showOn != 'always')
btnContainer.css('opacity', 0);
/* Event Bindings */
// bind hover events to show/hide buttons
if (showOn == 'hover' || showOn == 'both')
buttons.add(input)
.bind('mouseenter' + eventNamespace, function() {
setHoverDelay(function() {
hovered = true;
if (!self.focused || (showOn == 'hover')) // ignore focus flag if show on hover only
self.showButtons();
});
})
.bind('mouseleave' + eventNamespace, function hoverOut() {
setHoverDelay(function() {
hovered = false;
if (!self.focused || (showOn == 'hover')) // ignore focus flag if show on hover only
self.hideButtons();
});
});
buttons.hover(function() {
// ensure that both buttons have hover removed, sometimes they get left on
self.buttons.removeClass(hover);
if (!options.disabled)
$(this).addClass(hover);
}, function() {
$(this).removeClass(hover);
})
.mousedown(mouseDown)
.mouseup(mouseUp)
.mouseout(mouseUp);
if (msie)
// fixes dbl click not firing second mouse down in IE
buttons.dblclick(function() {
if (!options.disabled) {
// make sure any changes are posted
self._change();
self._doSpin((this === upButton ? 1 : -1) * options.step);
}
return false;
})
// fixes IE8 dbl click selection highlight
.bind('selectstart', function() {return false;});
input.bind('keydown' + eventNamespace, function(e) {
var dir, large, limit,
keyCode = e.keyCode; // shortcut for minimization
if (e.ctrl || e.alt) return true; // ignore these events
if (isSpecialKey(keyCode))
inSpecialKey = true;
if (inKeyDown) return false; // only one direction at a time, and suppress invalid keys
switch (keyCode) {
case up:
case pageUp:
dir = 1;
large = keyCode == pageUp;
break;
case down:
case pageDown:
dir = -1;
large = keyCode == pageDown;
break;
case right:
case left:
dir = (keyCode == right) ^ rtl ? 1 : -1;
break;
case home:
limit = self.options.min;
if (limit != null) self._setValue(limit);
return false;
case end:
limit = self.options.max;
limit = self.options.max;
if (limit != null) self._setValue(limit);
return false;
}
if (dir) { // only process if dir was set above
if (!inKeyDown && !options.disabled) {
keyDir = dir;
$(dir > 0 ? upButton : downButton).addClass(active);
inKeyDown = true;
self._startSpin(dir, large);
}
return false;
}
})
.bind('keyup' + eventNamespace, function(e) {
if (e.ctrl || e.alt) return true; // ignore these events
if (isSpecialKey(keyCode))
inSpecialKey = false;
switch (e.keyCode) {
case up:
case right:
case pageUp:
case down:
case left:
case pageDown:
buttons.removeClass(active)
self._stopSpin();
inKeyDown = false;
return false;
}
})
.bind('keypress' + eventNamespace, function(e) {
if (invalidKey(e.keyCode, e.charCode)) return false;
})
.bind('change' + eventNamespace, function() { self._change(); })
.bind('focus' + eventNamespace, function() {
function selectAll() {
self.element.select();
}
msie ? selectAll() : setTimeout(selectAll, 0); // add delay for Chrome, but breaks IE8
self.focused = true;
focusCtrl = self;
if (!hovered && (showOn == 'focus' || showOn == 'both')) // hovered will only be set if hover affects show
self.showButtons();
})
.bind('blur' + eventNamespace, function() {
self.focused = false;
if (!hovered && (showOn == 'focus' || showOn == 'both')) // hovered will only be set if hover affects show
self.hideButtons();
});
function isSpecialKey(keyCode) {
for (var i=0; i<validKeys.length; i++) // predefined list of special keys
if (validKeys[i] == keyCode) return true;
return false;
}
function invalidKey(keyCode, charCode) {
if (inSpecialKey) return false;
var ch = String.fromCharCode(charCode || keyCode),
options = self.options;
if ((ch >= '0') && (ch <= '9') || (ch == '-')) return false;
if (((self.places > 0) && (ch == options.point))
|| (ch == options.group)) return false;
return true;
}
// used to delay start of hover show/hide by 100 milliseconds
function setHoverDelay(callback) {
if (hoverDelay) {
// don't do anything if trying to set the same callback again
if (callback === hoverDelayCallback) return;
clearTimeout(hoverDelay);
}
hoverDelayCallback = callback;
hoverDelay = setTimeout(execute, 100);
function execute() {
hoverDelay = 0;
callback();
}
}
function mouseDown() {
if (!options.disabled) {
var input = self.element[0],
dir = (this === upButton ? 1 : -1);
input.focus();
input.select();
$(this).addClass(active);
inMouseDown = true;
self._startSpin(dir);
}
return false;
}
function mouseUp() {
if (inMouseDown) {
$(this).removeClass(active);
self._stopSpin();
inMouseDown = false;
}
return false;
}
},
_procOptions: function(init) {
var self = this,
input = self.element,
options = self.options,
min = options.min,
max = options.max,
step = options.step,
places = options.places,
maxlength = -1, temp;
// setup increment based on speed string
if (options.increment == 'slow')
options.increment = [{count: 1, mult: 1, delay: 250},
{count: 3, mult: 1, delay: 100},
{count: 0, mult: 1, delay: 50}];
else if (options.increment == 'fast')
options.increment = [{count: 1, mult: 1, delay: 250},
{count: 19, mult: 1, delay: 100},
{count: 80, mult: 1, delay: 20},
{count: 100, mult: 10, delay: 20},
{count: 0, mult: 100, delay: 20}];
if ((min == null) && ((temp = input.attr('min')) != null))
min = parseFloat(temp);
if ((max == null) && ((temp = input.attr('max')) != null))
max = parseFloat(temp);
if (!step && ((temp = input.attr('step')) != null))
if (temp != 'any') {
step = parseFloat(temp);
options.largeStep *= step;
}
options.step = step = step || options.defaultStep;
// Process step for decimal places if none are specified
if ((places == null) && ((temp = step + '').indexOf('.') != -1))
places = temp.length - temp.indexOf('.') - 1;
self.places = places;
if ((max != null) && (min != null)) {
// ensure that min is less than or equal to max
if (min > max) min = max;
// set maxlength based on min/max
maxlength = Math.max(Math.max(maxlength, options.format(max, places, input).length), options.format(min, places, input).length);
}
// only lookup input maxLength on init
if (init) self.inputMaxLength = input[0].maxLength;
temp = self.inputMaxLength;
if (temp > 0) {
maxlength = maxlength > 0 ? Math.min(temp, maxlength) : temp;
temp = Math.pow(10, maxlength) - 1;
if ((max == null) || (max > temp))
max = temp;
temp = -(temp + 1) / 10 + 1;
if ((min == null) || (min < temp))
min = temp;
}
if (maxlength > 0)
input.attr('maxlength', maxlength);
options.min = min;
options.max = max;
// ensures that current value meets constraints
self._change();
input.unbind(mouseWheelEventName + eventNamespace);
if (options.mouseWheel)
input.bind(mouseWheelEventName + eventNamespace, self._mouseWheel);
},
_mouseWheel: function(e) {
var self = $.data(this, 'spinner');
if (!self.options.disabled && self.focused && (focusCtrl === self)) {
// make sure changes are posted
self._change();
self._doSpin(((e.wheelDelta || -e.detail) > 0 ? 1 : -1) * self.options.step);
return false;
}
},
// sets an interval to call the _spin function
_setTimer: function(delay, dir, large) {
var self = this;
self._stopSpin();
self.timer = setInterval(fire, delay);
function fire() {
self._spin(dir, large);
}
},
// stops the spin timer
_stopSpin: function() {
if (this.timer) {
clearInterval(this.timer);
this.timer = 0;
}
},
// performs first step, and starts the spin timer if increment is set
_startSpin: function(dir, large) {
// shortcuts
var self = this,
options = self.options,
increment = options.increment;
// make sure any changes are posted
self._change();
self._doSpin(dir * (large ? self.options.largeStep : self.options.step));
if (increment && increment.length > 0) {
self.counter = 0;
self.incCounter = 0;
self._setTimer(increment[0].delay, dir, large);
}
},
// called by timer for each step in the spin
_spin: function(dir, large) {
// shortcuts
var self = this,
increment = self.options.increment,
curIncrement = increment[self.incCounter];
self._doSpin(dir * curIncrement.mult * (large ? self.options.largeStep : self.options.step));
self.counter++;
if ((self.counter > curIncrement.count) && (self.incCounter < increment.length-1)) {
self.counter = 0;
curIncrement = increment[++self.incCounter];
self._setTimer(curIncrement.delay, dir, large);
}
},
// actually spins the timer by a step
_doSpin: function(step) {
// shortcut
var self = this,
value = self.curvalue;
if (value == null)
value = (step > 0 ? self.options.min : self.options.max) || 0;
self._setValue(value + step);
},
// Parse the value currently in the field
_parseValue: function() {
var value = this.element.val();
return value ? this.options.parse(value, this.element) : null;
},
_validate: function(value) {
var options = this.options,
min = options.min,
max = options.max;
if ((value == null) && !options.allowNull)
value = this.curvalue != null ? this.curvalue : min || max || 0; // must confirm not null in case just initializing and had blank value
if ((max != null) && (value > max))
return max;
else if ((min != null) && (value < min))
return min;
else
return value;
},
_change: function() {
var self = this, // shortcut
value = self._parseValue(),
min = self.options.min,
max = self.options.max;
// don't reprocess if change was self triggered
if (!self.selfChange) {
if (isNaN(value))
value = self.curvalue;
self._setValue(value, true);
}
},
// overrides _setData to force option parsing
_setOption: function(key, value) {
$.Widget.prototype._setOption.call(this, key, value);
this._procOptions();
},
increment: function() {
this._doSpin(this.options.step);
},
decrement: function() {
this._doSpin(-this.options.step);
},
showButtons: function(immediate) {
var btnContainer = this.btnContainer.stop();
if (immediate)
btnContainer.css('opacity', 1);
else
btnContainer.fadeTo('fast', 1);
},
hideButtons: function(immediate) {
var btnContainer = this.btnContainer.stop();
if (immediate)
btnContainer.css('opacity', 0);
else
btnContainer.fadeTo('fast', 0);
this.buttons.removeClass(hover);
},
// Set the value directly
_setValue: function(value, suppressFireEvent) {
var self = this;
self.curvalue = value = self._validate(value);
self.element.val(value != null ?
self.options.format(value, self.places, self.element) :
'');
if (!suppressFireEvent) {
self.selfChange = true;
self.element.change();
self.selfChange = false;
}
},
// Set or retrieve the value
value: function(newValue) {
if (arguments.length) {
this._setValue(newValue);
// maintains chaining
return this.element;
}
return this.curvalue;
},
enable: function() {
this.buttons.removeClass(disabled);
this.element[0].disabled = false;
$.Widget.prototype.enable.call(this);
},
disable: function() {
this.buttons.addClass(disabled)
// in case hover class got left on
.removeClass(hover);
this.element[0].disabled = true;
$.Widget.prototype.disable.call(this);
},
destroy: function(target) {
this.wrapper.remove();
this.element.unbind(eventNamespace).css({ width: this.oWidth, marginRight: this.oMargin });
$.Widget.prototype.destroy.call(this);
}
});
})( jQuery );
And i have a group of 3 spinners written as:
<input type="text" id="rate"name="rate" class="spinner" value="0" />
On a click of a radio button I want this input box as well as the spinner to be disabled.
If i set the disabled="disabled" for then only input box is disabled but the spinner up button and down button works. I want that also to be disabled.
Secondly, I want this to happen to my 1 particular input box, if I change some property of spinner that happens to all the spinners which I don't want.
I've used the jQuery.ui.spinner 1.20 from GitHub and the disable option is working as you expect.
For instance in your code you can do:
$('#rate').spinner("disable"); // 'rate' is the HTML input id
Please ensure that the id of each input is different.
This will result in an input disabled as well as the spinner's buttons disabled.
Please, have a look at https://github.com/btburnett3/jquery.ui.spinner to download the latest version of this extension.

Categories

Resources