Get or set variable from another function - javascript

I am using this custom JavaScript range slider, and I want to be able to get and set the sliders value. I already implemented the set function. (If you have a better way of doing it, please let me know.) I'm having trouble implementing the getValue function
I tried doing the following:
function getValue() {
if (value) {
return value;
}
return;
}
And when I call that function, I get the following error:
Uncaught ReferenceError: getValue is not defined
Creating a global variable, is not an option. How can I get the sliders value?
To set or get the sliders value, I want to be able to do the following:
mySlider.Value = 17; // Set Value
var currentValue = mySlider.Value // Get Value
JSFiddle
function rangeSlider(elem, config, update) {
if (typeof update != "undefined" && update) {
var dragger = elem.getElementsByTagName('span')[0];
var range = elem.getElementsByTagName('div')[0];
var isVertical = config.vertical;
var rangeWidth = range[!isVertical ? 'offsetWidth' : 'offsetHeight'];
var rangeOffset = range[!isVertical ? 'offsetLeft' : 'offsetTop'];
var draggerWidth = dragger[!isVertical ? 'offsetWidth' : 'offsetHeight'];
dragger.style[!isVertical ? 'left' : 'top'] = (config.value / 100 * rangeWidth - (draggerWidth / 2)) + 'px';
return;
}
function getValue() {
if (value) {
return value;
}
return;
}
var html = document.documentElement,
range = document.createElement('div'),
dragger = document.createElement('span'),
down = false,
rangeWidth, rangeOffset, draggerWidth, cachePosition;
var defaults = {
value: 0, // set default value on initiation from `0` to `100` (percentage based)
vertical: false, // vertical or horizontal?
rangeClass: "", // add extra custom class for the range slider track
draggerClass: "", // add extra custom class for the range slider dragger
drag: function(v) { /* console.log(v); */ } // function to return the range slider value into something
};
for (var i in defaults) {
if (typeof config[i] == "undefined") config[i] = defaults[i];
}
function addEventTo(el, ev, fn) {
if (el.addEventListener) {
el.addEventListener(ev, fn, false);
} else if (el.attachEvent) {
el.attachEvent('on' + ev, fn);
} else {
el['on' + ev] = fn;
}
}
var isVertical = config.vertical;
elem.className = (elem.className + ' range-slider ' + (isVertical ? 'range-slider-vertical' : 'range-slider-horizontal')).replace(/^ +/, "");
range.className = ('range-slider-track ' + config.rangeClass).replace(/ +$/, "");
dragger.className = ('dragger ' + config.draggerClass).replace(/ +$/, "");
addEventTo(range, "mousedown", function(e) {
html.className = (html.className + ' no-select').replace(/^ +/, "");
rangeWidth = range[!isVertical ? 'offsetWidth' : 'offsetHeight'];
rangeOffset = range[!isVertical ? 'offsetLeft' : 'offsetTop'];
draggerWidth = dragger[!isVertical ? 'offsetWidth' : 'offsetHeight'];
down = true;
updateDragger(e);
return false;
});
addEventTo(document, "mousemove", function(e) {
updateDragger(e);
});
addEventTo(document, "mouseup", function(e) {
html.className = html.className.replace(/(^| )no-select( |$)/g, "");
down = false;
});
addEventTo(window, "resize", function(e) {
var woh = dragger[!isVertical ? 'offsetWidth' : 'offsetHeight'];
dragger.style[!isVertical ? 'left' : 'top'] = (((cachePosition / 100) * range[!isVertical ? 'offsetWidth' : 'offsetHeight']) - (woh / 2)) + 'px';
down = false;
});
function updateDragger(e) {
e = e || window.event;
var pos = !isVertical ? e.pageX : e.pageY;
if (!pos) {
pos = !isVertical ? e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft : e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
if (down && pos >= rangeOffset && pos <= (rangeOffset + rangeWidth)) {
dragger.style[!isVertical ? 'left' : 'top'] = (pos - rangeOffset - (draggerWidth / 2)) + 'px';
cachePosition = Math.round(((pos - rangeOffset) / rangeWidth) * 100);
config.drag(cachePosition);
}
}
function initDragger() {
var woh = dragger[!isVertical ? 'offsetWidth' : 'offsetHeight'];
cachePosition = ((config.value / 100) * range[!isVertical ? 'offsetWidth' : 'offsetHeight']);
dragger.style[!isVertical ? 'left' : 'top'] = (cachePosition - (woh / 2)) + 'px';
config.drag(config.value);
}
range.appendChild(dragger);
elem.appendChild(range);
initDragger();
}
var slid1 = document.getElementById('range-slider-1');
var btn = document.getElementById('btn');
var anotherBtn = document.getElementById('anotherBtn');
var resultP = document.getElementById('results');
rangeSlider(slid1, {
value: 10,
});
btn.onclick = function() {
rangeSlider(slid1, {
value: 50
}, 1);
}
anotherBtn.onclick = function() {
document.getElementById('results').innerHTML = "Your Current Value is: " + getValue();
}
.range-slider-track {
height: 20px;
}
.range-slider-track:before {
content: "";
display: block;
width: 100%;
height: 2px;
background-color: black;
}
.range-slider-track .dragger {
display: block;
width: 10px;
height: inherit;
position: relative;
background-color: red;
}
<div id="range-slider-1"></div>
<button id="btn">Set Value</button>
<button id="anotherBtn">Get Value</button>
<p id="results"></p>

The function "rangeSlider()" should be handled as an object, not as a function...
You have to create an object:
var mySlider = new rangeSlider(slid1, { value: 10,});
And you can obtain its value as:
mySlider.getValue()
Take a look at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

Paste this javascript into the original fiddle and sett it working:
function rangeSlider(elem, config, update) {
var this_ = this;
this.setValue = function(value) {
var dragger = this.config.elem.getElementsByTagName('span')[0];
var range = this.config.elem.getElementsByTagName('div')[0];
var rangeWidth = range[!this.config.vertical ? 'offsetWidth' : 'offsetHeight'];
var draggerWidth = dragger[!this.config.vertical ? 'offsetWidth' : 'offsetHeight'];
dragger.style[!this.config.vertical ? 'left' : 'top'] = (value / 100 * rangeWidth - (draggerWidth / 2)) + 'px';
this.config.value = value;
};
this.getValue = function() {
return this.config.value;
};
var html = document.documentElement,
range = document.createElement('div'),
dragger = document.createElement('span'),
down = false,
rangeWidth, rangeOffset, draggerWidth, cachePosition;
this.config = {
value: (config.value || 0), // set default value on initiation from `0` to `100` (percentage based)
vertical: (config.vertical || false), // vertical or horizontal?
rangeClass: "", // add extra custom class for the range slider track
draggerClass: "", // add extra custom class for the range slider dragger
drag: function(v) { /* console.log(v); */ }, // function to return the range slider value into something
elem: elem
};
addEventTo = function(el, ev, fn) {
if (el.addEventListener) {
el.addEventListener(ev, fn, false);
} else if (el.attachEvent) {
el.attachEvent('on' + ev, fn);
} else {
el['on' + ev] = fn;
}
}
elem.className = (elem.className + ' range-slider ' + (this.config.vertical ? 'range-slider-vertical' : 'range-slider-horizontal')).replace(/^ +/, "");
range.className = ('range-slider-track ' + config.rangeClass).replace(/ +$/, "");
dragger.className = ('dragger ' + config.draggerClass).replace(/ +$/, "");
addEventTo(range, "mousedown", function(e) {
html.className = (html.className + ' no-select').replace(/^ +/, "");
rangeWidth = range[!this_.config.vertical ? 'offsetWidth' : 'offsetHeight'];
rangeOffset = range[!this_.config.vertical ? 'offsetLeft' : 'offsetTop'];
draggerWidth = dragger[!this_.config.vertical ? 'offsetWidth' : 'offsetHeight'];
down = true;
updateDragger(e);
return false;
});
addEventTo(document, "mousemove", function(e) {
updateDragger(e);
});
addEventTo(document, "mouseup", function(e) {
html.className = html.className.replace(/(^| )no-select( |$)/g, "");
down = false;
});
addEventTo(window, "resize", function(e) {
var woh = dragger[!this.config.vertical ? 'offsetWidth' : 'offsetHeight'];
dragger.style[!this.config.vertical ? 'left' : 'top'] = (((cachePosition / 100) * range[!this.config.vertical ? 'offsetWidth' : 'offsetHeight']) - (woh / 2)) + 'px';
down = false;
});
function updateDragger(e) {
e = e || window.event;
var pos = !this_.config.vertical ? e.pageX : e.pageY;
if (!pos) {
pos = !this_.config.vertical ? e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft : e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
if (down && pos >= rangeOffset && pos <= (rangeOffset + rangeWidth)) {
dragger.style[!this_.config.vertical ? 'left' : 'top'] = (pos - rangeOffset - (draggerWidth / 2)) + 'px';
cachePosition = Math.round(((pos - rangeOffset) / rangeWidth) * 100);
this_.config.value = cachePosition;
this_.config.drag(cachePosition);
}
};
this.initDragger = function() {
var woh = dragger[!this.config.vertical ? 'offsetWidth' : 'offsetHeight'];
cachePosition = ((config.value / 100) * range[!this.config.vertical ? 'offsetWidth' : 'offsetHeight']);
dragger.style[!this.config.vertical ? 'left' : 'top'] = (cachePosition - (woh / 2)) + 'px';
this.config.drag(this.config.value);
};
range.appendChild(dragger);
elem.appendChild(range);
this.initDragger();
}
var slid1 = document.getElementById('range-slider-1');
var btn = document.getElementById('btn');
var anotherBtn = document.getElementById('anotherBtn');
var resultP = document.getElementById('results');
var rs = new rangeSlider(slid1, {
value: 10,
});
var slid2 = document.getElementById('range-slider-2');
var rs2 = new rangeSlider(slid2, {
value: 20,
});
btn.onclick = function() {
rs.setValue(50);
}
anotherBtn.onclick = function() {
document.getElementById('results').innerHTML = "Range 1: " + rs.getValue() + '<br/>Range2: ' + rs2.getValue();
}
And this html also:
<div id="range-slider-1"></div>
<button id="btn">Set Value</button>
<button id="anotherBtn">Get Value</button>
<div id="range-slider-2"></div>
<p id="results"></p>
Like some of the other posters said, you need to fix your function a bit.
I don't have time to clean up the new code, but I'm sure you'll get the idea.
Here are a few things to keep in mind:
You want to create a new object by calling new rangeSlider.
You can assign the new object to a variable so you can use that variable to set or get values.
Notice the var this_ = this statement so we'll have access to the object instance even certain events, because the this in those events may be the actual elements in the DOM.
This new approach supports the multiple sliders in the document, as with your original code, but it is a lot more simpler and cleaner to get and set values.
I'm sure we can clean this code a lot more, so enjoy.

Related

When value is x, display text next to value

I am creating a form that includes a budget slider with the following code
<div class="budget_slider">
<input type="range" name="budget" min="1" max="12" step="1" value="0" data-orientation="horizontal" onchange="getVals(this, 'budget');" style="position: absolute; width: 1px; height: 1px; overflow: hidden; opacity: 0;"><div class="rangeslider rangeslider--horizontal" id="js-rangeslider-0"><div class="rangeslider__fill" style="width: 10px;"></div><div class="rangeslider__handle" style="left: 0px;"></div></div><span>1</span>
</div>
It is a slider that goes from 1 to 12. When the slider hits 12, I want the value to show "12+" and not just "12". That is: when the slider is in any value between 1 and 11, just show that number, but the next value should be 12+, indicating that the client is willing to buy 12 or more items. Is there any way I can do that?
This is the rangeslider.js file:
/*! rangeslider.js - v2.3.0 | (c) 2016 #andreruffert | MIT license | https://github.com/andreruffert/rangeslider.js */
(function(factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function($) {
'use strict';
// Polyfill Number.isNaN(value)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
Number.isNaN = Number.isNaN || function(value) {
return typeof value === 'number' && value !== value;
};
/**
* Range feature detection
* #return {Boolean}
*/
function supportsRange() {
var input = document.createElement('input');
input.setAttribute('type', 'range');
return input.type !== 'text';
}
var pluginName = 'rangeslider',
pluginIdentifier = 0,
hasInputRangeSupport = supportsRange(),
defaults = {
polyfill: true,
orientation: 'horizontal',
rangeClass: 'rangeslider',
disabledClass: 'rangeslider--disabled',
activeClass: 'rangeslider--active',
horizontalClass: 'rangeslider--horizontal',
verticalClass: 'rangeslider--vertical',
fillClass: 'rangeslider__fill',
handleClass: 'rangeslider__handle',
startEvent: ['mousedown', 'touchstart', 'pointerdown'],
moveEvent: ['mousemove', 'touchmove', 'pointermove'],
endEvent: ['mouseup', 'touchend', 'pointerup']
},
constants = {
orientation: {
horizontal: {
dimension: 'width',
direction: 'left',
directionStyle: 'left',
coordinate: 'x'
},
vertical: {
dimension: 'height',
direction: 'top',
directionStyle: 'bottom',
coordinate: 'y'
}
}
};
/**
* Delays a function for the given number of milliseconds, and then calls
* it with the arguments supplied.
*
* #param {Function} fn [description]
* #param {Number} wait [description]
* #return {Function}
*/
function delay(fn, wait) {
var args = Array.prototype.slice.call(arguments, 2);
return setTimeout(function(){ return fn.apply(null, args); }, wait);
}
/**
* Returns a debounced function that will make sure the given
* function is not triggered too much.
*
* #param {Function} fn Function to debounce.
* #param {Number} debounceDuration OPTIONAL. The amount of time in milliseconds for which we will debounce the function. (defaults to 100ms)
* #return {Function}
*/
function debounce(fn, debounceDuration) {
debounceDuration = debounceDuration || 100;
return function() {
if (!fn.debouncing) {
var args = Array.prototype.slice.apply(arguments);
fn.lastReturnVal = fn.apply(window, args);
fn.debouncing = true;
}
clearTimeout(fn.debounceTimeout);
fn.debounceTimeout = setTimeout(function(){
fn.debouncing = false;
}, debounceDuration);
return fn.lastReturnVal;
};
}
/**
* Check if a `element` is visible in the DOM
*
* #param {Element} element
* #return {Boolean}
*/
function isHidden(element) {
return (
element && (
element.offsetWidth === 0 ||
element.offsetHeight === 0 ||
// Also Consider native `<details>` elements.
element.open === false
)
);
}
/**
* Get hidden parentNodes of an `element`
*
* #param {Element} element
* #return {[type]}
*/
function getHiddenParentNodes(element) {
var parents = [],
node = element.parentNode;
while (isHidden(node)) {
parents.push(node);
node = node.parentNode;
}
return parents;
}
/**
* Returns dimensions for an element even if it is not visible in the DOM.
*
* #param {Element} element
* #param {String} key (e.g. offsetWidth …)
* #return {Number}
*/
function getDimension(element, key) {
var hiddenParentNodes = getHiddenParentNodes(element),
hiddenParentNodesLength = hiddenParentNodes.length,
inlineStyle = [],
dimension = element[key];
// Used for native `<details>` elements
function toggleOpenProperty(element) {
if (typeof element.open !== 'undefined') {
element.open = (element.open) ? false : true;
}
}
if (hiddenParentNodesLength) {
for (var i = 0; i < hiddenParentNodesLength; i++) {
// Cache style attribute to restore it later.
inlineStyle[i] = hiddenParentNodes[i].style.cssText;
// visually hide
if (hiddenParentNodes[i].style.setProperty) {
hiddenParentNodes[i].style.setProperty('display', 'block', 'important');
} else {
hiddenParentNodes[i].style.cssText += ';display: block !important';
}
hiddenParentNodes[i].style.height = '0';
hiddenParentNodes[i].style.overflow = 'hidden';
hiddenParentNodes[i].style.visibility = 'hidden';
toggleOpenProperty(hiddenParentNodes[i]);
}
// Update dimension
dimension = element[key];
for (var j = 0; j < hiddenParentNodesLength; j++) {
// Restore the style attribute
hiddenParentNodes[j].style.cssText = inlineStyle[j];
toggleOpenProperty(hiddenParentNodes[j]);
}
}
return dimension;
}
/**
* Returns the parsed float or the default if it failed.
*
* #param {String} str
* #param {Number} defaultValue
* #return {Number}
*/
function tryParseFloat(str, defaultValue) {
var value = parseFloat(str);
return Number.isNaN(value) ? defaultValue : value;
}
/**
* Capitalize the first letter of string
*
* #param {String} str
* #return {String}
*/
function ucfirst(str) {
return str.charAt(0).toUpperCase() + str.substr(1);
}
/**
* Plugin
* #param {String} element
* #param {Object} options
*/
function Plugin(element, options) {
this.$window = $(window);
this.$document = $(document);
this.$element = $(element);
this.options = $.extend( {}, defaults, options );
this.polyfill = this.options.polyfill;
this.orientation = this.$element[0].getAttribute('data-orientation') || this.options.orientation;
this.onInit = this.options.onInit;
this.onSlide = this.options.onSlide;
this.onSlideEnd = this.options.onSlideEnd;
this.DIMENSION = constants.orientation[this.orientation].dimension;
this.DIRECTION = constants.orientation[this.orientation].direction;
this.DIRECTION_STYLE = constants.orientation[this.orientation].directionStyle;
this.COORDINATE = constants.orientation[this.orientation].coordinate;
// Plugin should only be used as a polyfill
if (this.polyfill) {
// Input range support?
if (hasInputRangeSupport) { return false; }
}
this.identifier = 'js-' + pluginName + '-' +(pluginIdentifier++);
this.startEvent = this.options.startEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
this.moveEvent = this.options.moveEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
this.endEvent = this.options.endEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
this.toFixed = (this.step + '').replace('.', '').length - 1;
this.$fill = $('<div class="' + this.options.fillClass + '" />');
this.$handle = $('<div class="' + this.options.handleClass + '" />');
this.$range = $('<div class="' + this.options.rangeClass + ' ' + this.options[this.orientation + 'Class'] + '" id="' + this.identifier + '" />').insertAfter(this.$element).prepend(this.$fill, this.$handle);
// visually hide the input
this.$element.css({
'position': 'absolute',
'width': '1px',
'height': '1px',
'overflow': 'hidden',
'opacity': '0'
});
// Store context
this.handleDown = $.proxy(this.handleDown, this);
this.handleMove = $.proxy(this.handleMove, this);
this.handleEnd = $.proxy(this.handleEnd, this);
this.init();
// Attach Events
var _this = this;
this.$window.on('resize.' + this.identifier, debounce(function() {
// Simulate resizeEnd event.
delay(function() { _this.update(false, false); }, 300);
}, 20));
this.$document.on(this.startEvent, '#' + this.identifier + ':not(.' + this.options.disabledClass + ')', this.handleDown);
// Listen to programmatic value changes
this.$element.on('change.' + this.identifier, function(e, data) {
if (data && data.origin === _this.identifier) {
return;
}
var value = e.target.value,
pos = _this.getPositionFromValue(value);
_this.setPosition(pos);
});
}
Plugin.prototype.init = function() {
this.update(true, false);
if (this.onInit && typeof this.onInit === 'function') {
this.onInit();
}
};
Plugin.prototype.update = function(updateAttributes, triggerSlide) {
updateAttributes = updateAttributes || false;
if (updateAttributes) {
this.min = tryParseFloat(this.$element[0].getAttribute('min'), 0);
this.max = tryParseFloat(this.$element[0].getAttribute('max'), 100);
this.value = tryParseFloat(this.$element[0].value, Math.round(this.min + (this.max-this.min)/2));
this.step = tryParseFloat(this.$element[0].getAttribute('step'), 1);
}
this.handleDimension = getDimension(this.$handle[0], 'offset' + ucfirst(this.DIMENSION));
this.rangeDimension = getDimension(this.$range[0], 'offset' + ucfirst(this.DIMENSION));
this.maxHandlePos = this.rangeDimension - this.handleDimension;
this.grabPos = this.handleDimension / 2;
this.position = this.getPositionFromValue(this.value);
// Consider disabled state
if (this.$element[0].disabled) {
this.$range.addClass(this.options.disabledClass);
} else {
this.$range.removeClass(this.options.disabledClass);
}
this.setPosition(this.position, triggerSlide);
};
Plugin.prototype.handleDown = function(e) {
e.preventDefault();
this.$document.on(this.moveEvent, this.handleMove);
this.$document.on(this.endEvent, this.handleEnd);
// add active class because Firefox is ignoring
// the handle:active pseudo selector because of `e.preventDefault();`
this.$range.addClass(this.options.activeClass);
// If we click on the handle don't set the new position
if ((' ' + e.target.className + ' ').replace(/[\n\t]/g, ' ').indexOf(this.options.handleClass) > -1) {
return;
}
var pos = this.getRelativePosition(e),
rangePos = this.$range[0].getBoundingClientRect()[this.DIRECTION],
handlePos = this.getPositionFromNode(this.$handle[0]) - rangePos,
setPos = (this.orientation === 'vertical') ? (this.maxHandlePos - (pos - this.grabPos)) : (pos - this.grabPos);
this.setPosition(setPos);
if (pos >= handlePos && pos < handlePos + this.handleDimension) {
this.grabPos = pos - handlePos;
}
};
Plugin.prototype.handleMove = function(e) {
e.preventDefault();
var pos = this.getRelativePosition(e);
var setPos = (this.orientation === 'vertical') ? (this.maxHandlePos - (pos - this.grabPos)) : (pos - this.grabPos);
this.setPosition(setPos);
};
Plugin.prototype.handleEnd = function(e) {
e.preventDefault();
this.$document.off(this.moveEvent, this.handleMove);
this.$document.off(this.endEvent, this.handleEnd);
this.$range.removeClass(this.options.activeClass);
// Ok we're done fire the change event
this.$element.trigger('change', { origin: this.identifier });
if (this.onSlideEnd && typeof this.onSlideEnd === 'function') {
this.onSlideEnd(this.position, this.value);
}
};
Plugin.prototype.cap = function(pos, min, max) {
if (pos < min) { return min; }
if (pos > max) { return max; }
return pos;
};
Plugin.prototype.setPosition = function(pos, triggerSlide) {
var value, newPos;
if (triggerSlide === undefined) {
triggerSlide = true;
}
// Snapping steps
value = this.getValueFromPosition(this.cap(pos, 0, this.maxHandlePos));
newPos = this.getPositionFromValue(value);
// Update ui
this.$fill[0].style[this.DIMENSION] = (newPos + this.grabPos) + 'px';
this.$handle[0].style[this.DIRECTION_STYLE] = newPos + 'px';
this.setValue(value);
// Update globals
this.position = newPos;
this.value = value;
if (triggerSlide && this.onSlide && typeof this.onSlide === 'function') {
this.onSlide(newPos, value);
}
};
// Returns element position relative to the parent
Plugin.prototype.getPositionFromNode = function(node) {
var i = 0;
while (node !== null) {
i += node.offsetLeft;
node = node.offsetParent;
}
return i;
};
Plugin.prototype.getRelativePosition = function(e) {
// Get the offset DIRECTION relative to the viewport
var ucCoordinate = ucfirst(this.COORDINATE),
rangePos = this.$range[0].getBoundingClientRect()[this.DIRECTION],
pageCoordinate = 0;
if (typeof e.originalEvent['client' + ucCoordinate] !== 'undefined') {
pageCoordinate = e.originalEvent['client' + ucCoordinate];
}
else if (
e.originalEvent.touches &&
e.originalEvent.touches[0] &&
typeof e.originalEvent.touches[0]['client' + ucCoordinate] !== 'undefined'
) {
pageCoordinate = e.originalEvent.touches[0]['client' + ucCoordinate];
}
else if(e.currentPoint && typeof e.currentPoint[this.COORDINATE] !== 'undefined') {
pageCoordinate = e.currentPoint[this.COORDINATE];
}
return pageCoordinate - rangePos;
};
Plugin.prototype.getPositionFromValue = function(value) {
var percentage, pos;
percentage = (value - this.min)/(this.max - this.min);
pos = (!Number.isNaN(percentage)) ? percentage * this.maxHandlePos : 0;
return pos;
};
Plugin.prototype.getValueFromPosition = function(pos) {
var percentage, value;
percentage = ((pos) / (this.maxHandlePos || 1));
value = this.step * Math.round(percentage * (this.max - this.min) / this.step) + this.min;
return Number((value).toFixed(this.toFixed));
};
Plugin.prototype.setValue = function(value) {
if (value === this.value && this.$element[0].value !== '') {
return;
}
// Set the new value and fire the `input` event
this.$element
.val(value)
.trigger('input', { origin: this.identifier });
};
Plugin.prototype.destroy = function() {
this.$document.off('.' + this.identifier);
this.$window.off('.' + this.identifier);
this.$element
.off('.' + this.identifier)
.removeAttr('style')
.removeData('plugin_' + pluginName);
// Remove the generated markup
if (this.$range && this.$range.length) {
this.$range[0].parentNode.removeChild(this.$range[0]);
}
};
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function(options) {
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function() {
var $this = $(this),
data = $this.data('plugin_' + pluginName);
// Create a new instance.
if (!data) {
$this.data('plugin_' + pluginName, (data = new Plugin(this, options)));
}
// Make it possible to access methods from public.
// e.g `$element.rangeslider('method');`
if (typeof options === 'string') {
data[options].apply(data, args);
}
});
};
return 'rangeslider.js is available in jQuery context e.g $(selector).rangeslider(options);';
}));
Thank you in advance!
I'm not 100% sure what exactly I am looking at above, but I won't be a jerk and vote down your question lol. Here's the basic idea of what you are trying to accomplish:
Create a condition in your JavaScript that applies to the numeric value of your range slider. If it's equal to 12 to set it equal to a string equal to "12+". This is pseudo code, but the basic idea would be:
if (numericValue == 12)
{displayedValue = "12+"}
If your range slider won't display a string value and requires and integer, then create a div tag with your "+" next to your numeric value and adjust it's visibility based on the value of your slider being equal to 12.
I would recommend not using the open source code you have above unless you absolutely have to. There is already a default range slider available in HTML that you can customize:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/range
Avoid open source projects where possible unless it's something you can't live without that isn't readily available.
Always sucks being a beginner, but hang in there, and it'll come together. Hope this gets you moving in the right direction.

Adding a SetInterval function in jquery

So I have this code from here: j360
This code is perfect for what I want: an html wich has a draggable 360º product image view, but it lacks one thing: a button for auto rotation.
I already have the button into the html, but I can't, for more that I try, to make a function or anything to make the images go by itself, and not only when I drag it over the screen.
Here is the code I have in the moment.
(function($){
$.fn.j360 = function(options) {
var defaults = {
clicked: false,
currImg: 1
}
var options = jQuery.extend(defaults, options);
return this.each(function() {
var $obj = jQuery(this);
var aImages = {};
$obj.css({
'margin-left' : 'auto',
'margin-right' : 'auto',
'text-align' : 'center',
'overflow' : 'hide'
});
$overlay = $obj.clone(true);
$overlay.html('<img src="images/loader.gif" class="loader" style="margin-top:' + ($obj.height()/2 - 15) + 'px" />');
$overlay.attr('id', 'view_overlay');
$overlay.css({
'position' : 'absolute',
'z-index': '5',
'top' : $obj.offset().top,
'left' : $obj.offset().left,
'background' : '#fff'
});
$obj.after($overlay);
$obj.after('<div id="colors_ctrls"></div>');
jQuery('#colors_ctrls').css({
'width' : $obj.width(),
'position' : 'absolute',
'z-index': '5',
'top' : $obj.offset().top + $obj.height - 50,
'left' : $obj.offset().left
});
var imageTotal = 0;
jQuery('img', $obj).each(function() {
aImages[++imageTotal] = jQuery(this).attr('src');
preload(jQuery(this).attr('src'));
})
var imageCount = 0;
jQuery('.preload_img').load(function() {
if (++imageCount == imageTotal) {
$overlay.animate({
'filter' : 'alpha(Opacity=0)',
'opacity' : 0
}, 100);
$obj.html('<img src="' + aImages[1] + '" />');
$overlay.bind('mousedown touchstart', function(e) {
if (e.type == "touchstart") {
options.currPos = window.event.touches[0].pageX;
} else {
options.currPos = e.pageX;
}
options.clicked = true;
return false;
});
jQuery(document).bind('mouseup touchend', function() {
options.clicked = false;
});
jQuery(document).bind('mousemove touchmove', function(e) {
if (options.clicked) {
var pageX;
if (e.type == "touchmove") {
pageX = window.event.targetTouches[0].pageX;
} else {
pageX = e.pageX;
}
var width_step = 50;
if (Math.abs(options.currPos - pageX) >= width_step) {
if (options.currPos - pageX >= width_step) {
options.currImg++;
if (options.currImg > imageTotal) {
options.currImg = 1;
}
} else {
options.currImg--;
if (options.currImg < 1) {
options.currImg = imageTotal;
}
}
options.currPos = pageX;
$obj.html('<img src="' + aImages[options.currImg] + '" />');
}
}
});
}
});
if (jQuery.browser.msie || jQuery.browser.mozilla || jQuery.browser.opera || jQuery.browser.safari ) {
jQuery(window).resize(function() {
onresizeFunc($obj, $overlay);
});
} else {
var supportsOrientationChange = "onorientationchange" in window,
orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";
window.addEventListener(orientationEvent, function() {
onresizeFunc($obj, $overlay);
}, false);
}
onresizeFunc($obj, $overlay)
});
}
})
(jQuery)
function onresizeFunc($obj, $overlay){
$obj.css({
'margin-top' : $(document).height()/2
});
$overlay.css({
'margin-top' : 200,
'top' : $obj.offset().top,
'left' : $obj.offset().left
});
jQuery('#colors_ctrls').css({
'top' : $obj.offset().top + $obj.height - 50,
'left' : $obj.offset().left
})
}
function preload(image) {
if (typeof document.body == "undefined") return;
try {
var div = document.createElement("div");
var s = div.style;
s.position = "absolute";
s.top = s.left = 0;
s.visibility = "hidden";
document.body.appendChild(div);
div.innerHTML = "<img class=\"preload_img\" src=\"" + image + "\" />";
}
catch(e) {
// Error. Do nothing.
}
};
I need a method to increment over time a function, to make the ilusion of auto-rotate.
This plugin doesn’t seem to have this option (a kind of autoplay) so you have to code it or search an other plugin.
Since it is a list of image, you can maybe don’t use the plugin and display images one after another with jQuery and .delay()

AngularJS $watch within directive not triggering

I have a watch looking at my sliders model and when I want to set one of the properties to visible or enabled it doesn't seem to want to fire the watch changed event. If I click the button it should hide or disable the handle and it does not. If I drag another handle the updateDOM is called and the handle is then hidden or disabled. Not sure what I am doing incorrectly here.
scope.$watch('sliders', function(oldValue, newValue) {
console.log('sliders Update: ', oldValue, ' : ', newValue);
updateDOM();
});
Here is a working plunk: http://plnkr.co/edit/I3A9H8qTs0z4CVaYnyJZ?p=preview
'use strict';
angular.module('angularMultiSlider', [])
.directive('multiSliderKey', function($compile) {
return {
restrict: 'EA',
transclude: true,
scope: {
displayFilter: '#',
sliders : '=ngModel'
},
link: function(scope, element) {
var sliderStr = '';
if (scope.displayFilter === undefined) scope.displayFilter = '';
var filterExpression = scope.displayFilter === '' ? '' : ' | ' + scope.displayFilter;
angular.forEach(scope.sliders, function(slider, key){
var colorKey = slider.color ? '<span style="background-color:' + slider.color + ';"></span> ' : '';
sliderStr += '<div class="key">' + colorKey + '{{ sliders[' + key.toString() + '].title }} <strong>{{ sliders[' + key.toString() + '].value ' + filterExpression + '}}</strong></div>';
});
var sliderControls = angular.element('<div class="angular-multi-slider-key">' + sliderStr + '</div>');
element.append(sliderControls);
$compile(sliderControls)(scope);
}
}
})
.directive('multiSlider', function($compile, $filter) {
var events = {
mouse: {
start: 'mousedown',
move: 'mousemove',
end: 'mouseup'
},
touch: {
start: 'touchstart',
move: 'touchmove',
end: 'touchend'
}
};
function roundStep(value, precision, step, floor) {
var remainder = (value - floor) % step;
var steppedValue = remainder > (step / 2) ? value + step - remainder : value - remainder;
var decimals = Math.pow(10, precision);
var roundedValue = steppedValue * decimals / decimals;
return parseFloat(roundedValue.toFixed(precision));
}
function offset(element, position) {
return element.css({
left: position
});
}
function pixelize(position) {
return parseInt(position) + 'px';
}
function contain(value) {
if (isNaN(value)) return value;
return Math.min(Math.max(0, value), 100);
}
function overlaps(b1, b2, offsetTop) {
function comparePositions(p1, p2) {
var r1 = p1[0] < p2[0] ? p1 : p2;
var r2 = p1[0] < p2[0] ? p2 : p1;
return r1[1] > r2[0] || r1[0] === r2[0];
}
var posB1 = [[ b1.offsetLeft, b1.offsetLeft + b1.offsetWidth ], [ offsetTop, offsetTop - b1.scrollTop + b1.offsetHeight ]],
posB2 = [[ b2.offsetLeft, b2.offsetLeft + b2.offsetWidth ], [ b2.offsetTop, b2.offsetTop - b2.scrollTop + b2.offsetHeight ]];
return comparePositions( posB1[0], posB2[0] ) && comparePositions( posB1[1], posB2[1] );
}
return {
restrict: 'EA',
require: '?ngModel',
scope: {
floor: '#',
ceiling: '#',
step: '#',
precision: '#',
bubbles: '#',
displayFilter: '#',
sliders: '=ngModel'
},
template :
'<div class="bar"></div>',
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
//base copy to see if sliders returned to original
var original;
ngModel.$render = function() {
original = angular.copy(scope.sliders);
};
element.addClass('angular-multi-slider');
// DOM Components
if (scope.displayFilter === undefined) scope.displayFilter = '';
var filterExpression = scope.displayFilter === '' ? '' : ' | ' + scope.displayFilter;
var sliderStr = '<div class="limit floor">{{ floor ' + filterExpression + ' }}</div>' +
'<div class="limit ceiling">{{ ceiling ' + filterExpression + '}}</div>';
angular.forEach(scope.sliders, function(slider, key){
sliderStr += '<div class="handle"></div><div class="bubble">{{ sliders[' + key.toString() + '].title }}{{ sliders[' + key.toString() + '].value ' + filterExpression + ' }}</div>';
});
var sliderControls = angular.element(sliderStr);
element.append(sliderControls);
$compile(sliderControls)(scope);
var children = element.children();
var bar = angular.element(children[0]),
ngDocument = angular.element(document),
floorBubble = angular.element(children[1]),
ceilBubble = angular.element(children[2]),
bubbles = [],
handles = [];
angular.forEach(scope.sliders, function(slider, key) {
handles.push(angular.element(children[(key * 2) + 3]));
bubbles.push(angular.element(children[(key * 2) + 4]));
});
// Control Dimensions Used for Calculations
var handleHalfWidth = 0,
barWidth = 0,
minOffset = 0,
maxOffset = 0,
minValue = 0,
maxValue = 0,
valueRange = 0,
offsetRange = 0,
bubbleTop = undefined,
bubbleHeight = undefined,
handleTop = undefined,
handleHeight = undefined;
if (scope.step === undefined) scope.step = 10;
if (scope.floor === undefined) scope.floor = 0;
if (scope.ceiling === undefined) scope.ceiling = 500;
if (scope.precision === undefined) scope.precision = 2;
if (scope.bubbles === undefined) scope.bubbles = false;
var bindingsSet = false;
var updateCalculations = function() {
scope.floor = roundStep(parseFloat(scope.floor), parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
scope.ceiling = roundStep(parseFloat(scope.ceiling), parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
angular.forEach(scope.sliders, function(slider) {
slider.value = roundStep(parseFloat(slider.value), parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
});
handleHalfWidth = handles[0][0].offsetWidth / 2;
barWidth = bar[0].offsetWidth;
minOffset = 0;
maxOffset = barWidth - handles[0][0].offsetWidth;
minValue = parseFloat(scope.floor);
maxValue = parseFloat(scope.ceiling);
valueRange = maxValue - minValue;
offsetRange = maxOffset - minOffset;
};
var updateDOM = function () {
updateCalculations();
var percentOffset = function (offset) {
return contain(((offset - minOffset) / offsetRange) * 100);
};
var percentValue = function (value) {
return contain(((value - minValue) / valueRange) * 100);
};
var pixelsToOffset = function (percent) {
return pixelize(percent * offsetRange / 100);
};
var setHandles = function () {
offset(ceilBubble, pixelize(barWidth - ceilBubble[0].offsetWidth));
angular.forEach(scope.sliders, function(slider,key){
if (slider.color) {
handles[key].css({'background-color': slider.color});
}
if (slider.value >= minValue && slider.value <= maxValue) {
offset(handles[key], pixelsToOffset(percentValue(slider.value)));
offset(bubbles[key], pixelize(handles[key][0].offsetLeft - (bubbles[key][0].offsetWidth / 2) + handleHalfWidth));
handles[key].css({'display': 'block'});
if ('' + scope.bubbles === 'true') {
bubbles[key].css({'display': 'block'});
}
} else {
handles[key].css({'display': 'none'});
bubbles[key].css({'display': 'none'});
}
if (slider.hasOwnProperty("visible") && slider.visible === false) {
handles[key].css({'display': 'none'});
bubbles[key].css({'display': 'none'});
}
if (slider.hasOwnProperty("enabled") && slider.enabled === false) {
handles[key].addClass('disabled');
bubbles[key].addClass('disabled');
} else {
handles[key].removeClass('disabled');
bubbles[key].removeClass('disabled');
}
});
};
var resetBubbles = function() {
if (scope.sliders.length > 1) {
//timeout must be longer than css animation for proper bubble collision detection
for (var i = 0; i < scope.sliders.length; i++) {
(function (index) {
setTimeout(function () {
overlapCheck(index);
}, i * 150);
})(i);
}
}
};
var overlapCheck = function(currentRef) {
var safeAtLevel = function(cRef, level) {
for (var x = 0; x < scope.sliders.length; x++) {
if (x != cRef && overlaps(bubbles[cRef][0], bubbles[x][0], (bubbleTop * level))) {
return safeAtLevel(cRef, level + 1);
}
}
return level;
};
if (scope.sliders.length > 1) {
var safeLevel = safeAtLevel(currentRef, 1) - 1;
handles[currentRef].css({top: pixelize((-1 * (safeLevel * bubbleHeight)) + handleTop), height: pixelize(handleHeight + (bubbleHeight * safeLevel)), 'z-index': 99-safeLevel});
bubbles[currentRef].css({top: pixelize(bubbleTop - (bubbleHeight * safeLevel))});
}
};
var bind = function (handle, bubble, currentRef, events) {
var onEnd = function () {
handle.removeClass('grab');
bubble.removeClass('grab');
if (!(''+scope.bubbles === 'true')) {
bubble.removeClass('active');
}
ngDocument.unbind(events.move);
ngDocument.unbind(events.end);
if (angular.equals(scope.sliders, original)) {
ngModel.$setPristine();
}
//Move possible elevated bubbles back down if one below it moved.
resetBubbles();
scope.$apply();
};
var onMove = function (event) {
// Suss out which event type we are capturing and get the x value
var eventX = 0;
if (event.clientX !== undefined) {
eventX = event.clientX;
}
else if ( event.touches !== undefined && event.touches.length) {
eventX = event.touches[0].clientX;
}
else if ( event.originalEvent !== undefined &&
event.originalEvent.changedTouches !== undefined &&
event.originalEvent.changedTouches.length) {
eventX = event.originalEvent.changedTouches[0].clientX;
}
var newOffset = Math.max(Math.min((eventX - element[0].getBoundingClientRect().left - handleHalfWidth), maxOffset), minOffset),
newPercent = percentOffset(newOffset),
newValue = minValue + (valueRange * newPercent / 100.0);
newValue = roundStep(newValue, parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
scope.sliders[currentRef].value = newValue;
setHandles();
overlapCheck(currentRef);
ngModel.$setDirty();
scope.$apply();
};
var onStart = function (event) {
if (scope.sliders[currentRef].hasOwnProperty("enabled") && scope.sliders[currentRef].enabled === false) {
bubble.addClass('disabled');
handle.addClass('disabled');
return;
}
updateCalculations();
bubble.addClass('active grab');
handle.addClass('active grab');
setHandles();
event.stopPropagation();
event.preventDefault();
ngDocument.bind(events.move, onMove);
return ngDocument.bind(events.end, onEnd);
};
handle.bind(events.start, onStart);
};
var setBindings = function () {
var method, i;
var inputTypes = ['touch', 'mouse'];
for (i = 0; i < inputTypes.length; i++) {
method = inputTypes[i];
angular.forEach(scope.sliders, function(slider, key){
bind(handles[key], bubbles[key], key, events[method]);
if (scope.sliders[key].hasOwnProperty("enabled") && scope.sliders[key].enabled === false) {
handles[key].addClass('disabled');
bubbles[key].addClass('disabled');
}
});
}
bindingsSet = true;
};
if (!bindingsSet) {
setBindings();
// Timeout needed because bubbles offsetWidth is incorrect during initial rendering of html elements
setTimeout( function() {
if ('' + scope.bubbles === 'true') {
angular.forEach(bubbles, function (bubble) {
bubble.addClass('active');
});
}
updateCalculations();
setHandles();
//Get Default sizes of bubbles and handles, assuming each are equal, calculated from css
handleTop = handleTop === undefined ? handles[0][0].offsetTop : handleTop;
handleHeight = handleHeight === undefined ? handles[0][0].offsetHeight : handleHeight;
bubbleTop = bubbleTop === undefined ? bubbles[0][0].offsetTop : bubbleTop;
bubbleHeight = bubbleHeight === undefined ? bubbles[0][0].offsetHeight + 7 : bubbleHeight ; //add 7px bottom margin to the bubble offset for handle
resetBubbles();
}, 10);
}
};
// Watch Models based on mode
scope.$watch('sliders', function(oldValue, newValue) {
console.log('sliders Update: ', oldValue, ' : ', newValue);
updateDOM();
});
scope.$watch('ceiling', function() {
bindingsSet = false;
updateDOM();
});
scope.$watch('floor', function() {
bindingsSet = false;
updateDOM();
});
// Update on Window resize
window.addEventListener('resize', updateDOM);
}
}
});
I found the solution here: How to deep watch an array in angularjs? Deep watch /property watch.
$scope.$watch('columns', function() {
// some value in the array has changed
}, true); // watching properties

Uncaught SyntaxError: Unexpected token < in dev_touch.js

I am new to jquery. I have found this code for getting touch events. but it shows this. I don't know how to solve this problem.
error message
Uncaught SyntaxError: Unexpected token < in dev_touch.js
My code :
dev_touch.js
;(function($) {
'use strict'
var $html = $('html');
mainBody = main.find('body');
main.addClass("dev_toucher");
mainBody.append("<div></div>").attr("class", "dev_ui_toucher");
if (typeof $html.createEvent !== 'function') return false // no tap events here
// helpers
var useJquery = typeof jQuery !== 'undefined',
msPointerEnabled = !!navigator.pointerEnabled || navigator.msPointerEnabled,
isTouch = (!!('ontouchstart' in win) && navigator.userAgent.indexOf('PhantomJS') < 0) || msPointerEnabled,
msEventType = function(type) {
var lo = type.toLowerCase(),
ms = 'MS' + type
return navigator.msPointerEnabled ? ms : lo
},
touchevents = {
touchstart: msEventType('PointerDown') + ' touchstart',
touchend: msEventType('PointerUp') + ' touchend',
touchmove: msEventType('PointerMove') + ' touchmove'
},
setListener = function(elm, events, callback) {
var eventsArray = events.split(' '),
i = eventsArray.length
while (i--) {
elm.addEventListener(eventsArray[i], callback, false)
}
},
getPointerEvent = function(event) {
return event.targetTouches ? event.targetTouches[0] : event
},
getTimestamp = function () {
return new Date().getTime()
},
sendEvent = function(elm, eventName, originalEvent, data) {
var customEvent = $html.createEvent('Event')
customEvent.originalEvent = originalEvent
data = data || {}
data.x = currX
data.y = currY
data.distance = data.distance
// jquery
if (useJquery) {
customEvent = $.Event(eventName, {originalEvent: originalEvent})
jQuery(elm).trigger(customEvent, data)
}
// addEventListener
if (customEvent.initEvent) {
for (var key in data) {
customEvent[key] = data[key]
}
customEvent.initEvent(eventName, true, true)
elm.dispatchEvent(customEvent)
}
// inline
if (elm['on' + eventName])
elm['on' + eventName](customEvent)
},
onTouchStart = function(e) {
var pointer = getPointerEvent(e)
// caching the current x
cachedX = currX = pointer.pageX
// caching the current y
cachedY = currY = pointer.pageY
timestamp = getTimestamp()
tapNum++
// we will use these variables on the touchend events
},
onTouchEnd = function(e) {
var eventsArr = [],
now = getTimestamp(),
deltaY = cachedY - currY,
deltaX = cachedX - currX
// clear the previous timer in case it was set
clearTimeout(tapTimer)
if (deltaX <= -swipeThreshold)
eventsArr.push('swiperight')
if (deltaX >= swipeThreshold)
eventsArr.push('swipeleft')
if (deltaY <= -swipeThreshold)
eventsArr.push('swipedown')
if (deltaY >= swipeThreshold)
eventsArr.push('swipeup')
if (eventsArr.length) {
for (var i = 0; i < eventsArr.length; i++) {
var eventName = eventsArr[i]
sendEvent(e.target, eventName, e, {
distance: {
x: Math.abs(deltaX),
y: Math.abs(deltaY)
}
})
}
} else {
if (
cachedX >= currX - tapPrecision &&
cachedX <= currX + tapPrecision &&
cachedY >= currY - tapPrecision &&
cachedY <= currY + tapPrecision
){
if((timestamp + tapThreshold) - now >= 0){
// Here you get the Tap event
sendEvent(e.target, (tapNum === 2) && (target === e.target) ? 'dbltap' : 'tap', e)
target= e.target
}
else if((timestamp + longtapThreshold) - now <= 0){
// Here you get the Tap event
sendEvent(e.target,'longtap', e)
target= e.target
}
}
// reset the tap counter
tapTimer = setTimeout(function() {
tapNum = 0
}, dbltapThreshold)
}
},
onTouchMove = function(e) {
var pointer = getPointerEvent(e)
currX = pointer.pageX
currY = pointer.pageY
},
swipeThreshold = win.SWIPE_THRESHOLD || 100,
tapThreshold = win.TAP_THRESHOLD || 150, // range of time where a tap event could be detected
dbltapThreshold = win.DBL_TAP_THRESHOLD || 200, // delay needed to detect a double tap
longtapThreshold = win.LONG_TAP_THRESHOLD || 1000, // delay needed to detect a long tap
tapPrecision = win.TAP_PRECISION / 2 || 60 / 2, // touch events boundaries ( 60px by default )
justTouchEvents = win.JUST_ON_TOUCH_DEVICES || isTouch,
tapNum = 0,
currX, currY, cachedX, cachedY, tapTimer, timestamp, target
//setting the events listeners
setListener($html, touchevents.touchstart + (justTouchEvents ? '' : ' mousedown'), onTouchStart)
setListener($html, touchevents.touchend + (justTouchEvents ? '' : ' mouseup'), onTouchEnd)
setListener($html, touchevents.touchmove + (justTouchEvents ? '' : ' mousemove'), onTouchMove)
//test.on('tap',updateHtml);
//test.on('dbltap',updateHtml);
//test.on('longtap',updateHtml);
//test.on('swipeup',updateHtml);
//test.on('swipedown',updateHtml);
//test.on('swipeleft',updateHtml);
//test.on('swiperight',updateHtml);
}(document, window))
Can anyone help ?
I would be willing to be that you're being served an HTML file instead of your JavaScript file. Here's how to check:
Right-click anywhere on the page
Select 'Inspect Element'
Find your JS file and examine the contents.
See the picture for a pictorial representation with Firefox.

Javascript prototype working

I have HTML application and someone wrote javascript library for that which is used for scrolling. Now i want to scroll to particular div with that library and i dont have to use location.href or `location.hash`` I have to do this with the JS library the code is something like this..
var ScrollPage = BGBiRepScroller.ScrollPage = function(){
this.animationFunList = [];
}
ScrollPage.prototype = {
$el:null,
$sectionList:null,
sectionPositionsY:null,
startTouchY:0,
startScrollY:0,
initTop:0,
endTouchY:0,
endDistance:0,
acceleration:8,
containerHeight:600,
currentSectionIndex:0,
isScrolling:false,
snapSection:true,
create: function($tEl){
this.$el = $tEl;
this.sectionPositionsY = new Array();
this.$sectionList = this.$el.find(".scrollSection");
var $origParent = this.$el.parent();
var $tempHolder = $("<div></div>");
$("body").append($tempHolder);
$tempHolder.css("opacity",0);
$tempHolder.append(this.$el);
this.$el.transition({ y: 0},0);
if(this.$sectionList.length>0){
this.initTop = this.$sectionList.position().top;
console.log("this.initTop::" + this.initTop);
for(var i=0; i<this.$sectionList.length; i++){
this.sectionPositionsY.push($(this.$sectionList[i]).position().top);
console.log($(this.$sectionList[i]).position().top);
}
}
$origParent.prepend(this.$el);
$tempHolder.remove();
this.createTouchEvents();
},
createTouchEvents: function(){
if(this.$el){
this.$el[0].ScrollPage = this;
this.$el.on(BGBiRep.Events.TOUCH_START, this._onTouchStart);
this.$el.on(BGBiRep.Events.TOUCH_END, this._onTouchEnd);
if(BGBiRep.isTouchDevice){
this.$el.on(BGBiRep.Events.TOUCH_MOVE, this._onTouchMove);
}
}
},
getSnapToY: function(_y){
var middleY = _y - this.containerHeight*.5;
if(this.snapSection){
for(var i=0; i<this.$sectionList.length; i++){
var $_currentEl = $(this.$sectionList[i]),
elTop = this.sectionPositionsY[i]-this.initTop;
if(-middleY<elTop){
//console.log('getSnapToY: middleY::' + middleY + ' ::elTop::' + elTop + ' ::this.initTop::' + this.initTop);
return 0;
}else if((-middleY>=elTop && -middleY<=elTop+$_currentEl.height()+10) || i==this.$sectionList.length-1){
//console.log("entering :: " + i);
this.currentSectionIndex = i;
if(i==0){return 0;}
return -(elTop - (this.containerHeight - $_currentEl.height())*.5);
}
}
}else{
console.log('_y::' + _y);
if(_y<-this.$el.find(".col1").height() + 550){
return -this.$el.find(".col1").height()+550;
}else if(_y>0){
return 0;
}else{
return _y;
}
}
return 0;
},
addAnimation: function(_sectionName, _function){
this.animationFunList.push(new Array(_sectionName, _function));
},
getAnimation: function(_sectionName){
for(var i=0; i<this.animationFunList.length; i++){
if(this.animationFunList[i][0] == _sectionName){
return this.animationFunList[i][1];
}
}
},
stopTransition: function(){
this.$el.css("transition", "transform 0s");
this.$el.css("-webkit-transition", "transform 0s");
},
_onTouchStart: function(event, touch){
var touch ;
this.ScrollPage.isScrolling = true;
if(BGBiRep.isTouchDevice){
touch = event.originalEvent.touches[0] || event.originalEvent.changedTouches[0];
}
var transformY = parseFloat(String(this.ScrollPage.$el.css('translate')).split(',')[1]) ;
this.ScrollPage.startTouchY = this.ScrollPage.endTouchY = (BGBiRep.isTouchDevice) ? touch.pageY : event.pageY;
this.ScrollPage.startScrollY = transformY;
if(!BGBiRep.isTouchDevice){
this.ScrollPage.$el.on(BGBiRep.Events.TOUCH_MOVE, this.ScrollPage._onTouchMove);
}
this.ScrollPage.stopTransition();
//this.ScrollPage.$el.css('-webkit-transition', '');
//this.ScrollPage.$el.css('transition', '');
},
_onTouchMove: function(event){
event.preventDefault();
var touch ;
this.ScrollPage.isScrolling = true;
if(BGBiRep.isTouchDevice){
touch = event.originalEvent.targetTouches[0];
}
var tY = (BGBiRep.isTouchDevice) ? touch.pageY : event.pageY;
var transY = this.ScrollPage.startScrollY - (this.ScrollPage.startTouchY - tY);
var maxY = (this.ScrollPage.snapSection)?(-this.ScrollPage.sectionPositionsY[this.ScrollPage.$sectionList.length-1]+this.ScrollPage.initTop):-this.ScrollPage.$el.find(".col1").height() + 580;
if(this.ScrollPage.currentSectionIndex == 0 && transY>0){
transY=0;
}else if(this.ScrollPage.currentSectionIndex == this.ScrollPage.$sectionList.length-1 && transY<maxY){
transY = maxY;
}else if(!this.ScrollPage.snapSection && transY<maxY){
transY = maxY;
}
this.ScrollPage.$el.transition({ y: transY},0);
this.ScrollPage.endDistance = this.ScrollPage.endTouchY-tY;
this.ScrollPage.endTouchY = tY;
},
_onTouchEnd: function(event, touch){
if(!BGBiRep.isTouchDevice){
this.ScrollPage.$el.off(BGBiRep.Events.TOUCH_MOVE, this.ScrollPage._onTouchMove);
}
if(this.ScrollPage.isScrolling){
var newY = this.ScrollPage.startScrollY - (this.ScrollPage.startTouchY - this.ScrollPage.endTouchY) - this.ScrollPage.endDistance*this.ScrollPage.acceleration;
console.log("newY::" + newY + "::" + this.ScrollPage.startScrollY + "-" + (this.ScrollPage.startTouchY - this.ScrollPage.endTouchY) + "-" +this.ScrollPage.endDistance*this.ScrollPage.acceleration);
this.ScrollPage.startScrollY = this.ScrollPage.startTouchY = this.ScrollPage.endTouchY = this.ScrollPage.endDistance=0;
//console.log("newY::-310::" + this.ScrollPage.getSnapToY(-310));
var tSCCROLL = this.ScrollPage;
this.ScrollPage.$el.css('-webkit-transition', '');
this.ScrollPage.$el.css('transition', '');
var tSnap =this.ScrollPage.getSnapToY(newY);
var transformY = parseFloat(String(this.ScrollPage.$el.css('translate')).split(',')[1]) ;
console.log('tSCCROLL.currentSectionIndex ' +tSCCROLL.currentSectionIndex);
var tFun = function(){
var tDid = $(tSCCROLL.$sectionList[tSCCROLL.currentSectionIndex]).attr("data-id");
console.log('inside tFun');
if(tDid && tDid!=''){
console.log('inside tDid');
tSCCROLL.getAnimation(tDid)();
console.log(tSCCROLL.getAnimation(tDid));
}
}
if(tSnap!=transformY){
tFun();
this.ScrollPage.$el.transition({ y: tSnap}, tFun);
}
}
this.ScrollPage.isScrolling = false;
}
}
There are section of div now on click i want to move to a particular section
$('.purple li').click(function(e)
{
//SOMETHING
});
How could i achieve this please someone help

Categories

Resources