I am trying to make a function which will close my tooltip by 'click' on the parent element which returns me this tooltip by first click on it. Need to get the closing function exclusively for tooltip parent element. Right now everything is working, but i can also close my tooltip by clicking anywhere on body element.
`(function () {
function Tooltip(options) {
if (!options) options = {};
var self = this;
this.tooltips;
this.offset = 5;
this.beforeTooltip = options.beforeTooltip;
this.afterTooltip = options.afterTooltip;
this.tooltipWrapper = document.createElement('div');
this.status = false;
this.tooltip = function (elem) {
if (!elem.classList.contains('active')){
if (this.status) this.remElemActive();
if (this.beforeTooltip) this.beforeTooltip(elem);
elem.classList.add('active');
var coords = this.getCoords(elem);
this.tooltipWrapper.textContent = elem.dataset.tooltip;
this.tooltipWrapper.classList.add('active');
this.tooltipWrapper.style.top = coords.top - (this.tooltipWrapper.offsetHeight + this.offset) + 'px';
this.tooltipWrapper.style.left = (coords.left + coords.width / 2) - (this.tooltipWrapper.offsetWidth / 2) + 'px';
this.status = true;
if (this.status){
setTimeout(function () {
document.addEventListener('click', self.closeTipsBody, false);
}, 100)
}
if (this.afterTooltip) this.afterTooltip(elem)
}else {
elem.classList.remove('active');
}
};
this.closeTipsBody = function (e) {
if (self.tooltipWrapper === e.target || e.target.classList.contains('active')){
return false
}
self.closeTips();
};
this.closeTips = function () {
this.tooltipWrapper.classList.remove('active');
this.remElemActive();
this.status = false;
document.removeEventListener('click', self.closeTipsBody, false)
};
this.remElemActive = function () {
document.querySelector('.tooltip-js').classList.remove('active')
};
this.getCoords = function (elem) {
elem = elem.getBoundingClientRect();
return{
top: elem.top + window.pageYOffset,
left: elem.left + window.pageXOffset,
width: elem.width
}
};
this.init = function () {
document.addEventListener('DOMContentLoaded', function () {
this.tooltips = document.querySelectorAll('.tooltip-js');
this.tooltipWrapper.classList.add('tooltip-box');
document.querySelector('body').appendChild(this.tooltipWrapper);
for (var i = 0; i < this.tooltips.length; i++ ){
this.tooltips[i].addEventListener('click', function (e) {
e.preventDefault();
self.tooltip(this);
})
}
}.bind(this))
};
this.init();
}
window.Tooltip = Tooltip;
})();`
if you need any additional info, about what do i want to get to, text me.
I am using videojs in my react application. I have added rangeslider to it. There is a button near my video player which triggers the rangeslider to show up on the video player. Every thing works fine, but the rangeslider's start arrow is not at the point (time) where I clicked the button. The starting button is always at time 0:0. What I want is: say the video is playing at the current time 30:00 seconds and I clicked the show button, then rangeslider should show it's starting arrow at 30 sec only and not at o sec. I can get my current time of videojs player and pass it to rangeslider.js plugin, but I don't know where to pass it.
This is my rangeslider.js (I know it's a long code but i don't know which part of it to use to achieve the result)
//----------------Load Plugin----------------//
(function () {
var videojsAddClass = function (element, className) {
element.classList.add(className);
};
var videojsRemoveClass = function (element, className) {
element.classList.remove(className);
};
var videojsFindPosition = function (element) {
return element.getBoundingClientRect();
};
var videojsRound = function (n, precision) {
return parseFloat(n.toFixed(precision));
};
var videojsFormatTime = function (totalSeconds) {
var minutes = Math.floor(totalSeconds / 60).toFixed(0);
var seconds = (totalSeconds % 60).toFixed(0);
if (seconds.length === 1) {
seconds = "0" + seconds;
}
return minutes + ':' + seconds;
};
var videojsBlockTextSelection = function () {
// TODO
};
//-- Load RangeSlider plugin in videojs
function RangeSlider_(options) {
var player = this;
player.rangeslider = new RangeSlider(player, options);
//When the DOM and the video media is loaded
function initialVideoFinished(event) {
var plugin = player.rangeslider;
//All components will be initialize after they have been loaded by videojs
for (var index in plugin.components) {
plugin.components[index].init_();
}
if (plugin.options.hidden)
plugin.hide(); //Hide the Range Slider
if (plugin.options.locked)
plugin.lock(); //Lock the Range Slider
if (plugin.options.panel == false)
plugin.hidePanel(); //Hide the second Panel
if (plugin.options.controlTime == false)
plugin.hidecontrolTime(); //Hide the control time panel
plugin._reset();
player.trigger('loadedRangeSlider'); //Let know if the Range Slider DOM is ready
}
if (player.techName == 'Youtube') {
//Detect youtube problems
player.one('error', function (e) {
switch (player.error) {
case 2:
alert("The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.");
case 5:
alert("The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.");
case 100:
alert("The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.");
break;
case 101:
alert("The owner of the requested video does not allow it to be played in embedded players.");
break;
case 150:
alert("The owner of the requested video does not allow it to be played in embedded players.");
break;
default:
alert("Unknown Error");
break;
}
});
player.on('firstplay', initialVideoFinished);
} else {
player.one('playing', initialVideoFinished);
}
}
videojs.plugin('rangeslider', RangeSlider_);
//-- Plugin
function RangeSlider(player, options) {
var player = player || this;
this.player = player;
this.components = {}; // holds any custom components we add to the player
options = options || {}; // plugin options
if (!options.hasOwnProperty('locked'))
options.locked = false; // lock slider handles
if (!options.hasOwnProperty('hidden'))
options.hidden = true; // hide slider handles
if (!options.hasOwnProperty('panel'))
options.panel = true; // Show Second Panel
if (!options.hasOwnProperty('controlTime'))
options.controlTime = true; // Show Control Time to set the arrows in the edition
this.options = options;
this.init();
}
//-- Methods
RangeSlider.prototype = {
/*Constructor*/
init: function () {
var player = this.player || {};
this.updatePrecision = 3;
//position in second of the arrows
this.start = 0;
this.end = 0;
//components of the plugin
var controlBar = player.controlBar;
var seekBar = controlBar.progressControl.seekBar;
this.components.RSTimeBar = seekBar.RSTimeBar;
this.components.ControlTimePanel = controlBar.ControlTimePanel;
//Save local component
this.rstb = this.components.RSTimeBar;
this.box = this.components.SeekRSBar = this.rstb.SeekRSBar;
this.bar = this.components.SelectionBar = this.box.SelectionBar;
this.left = this.components.SelectionBarLeft = this.box.SelectionBarLeft;
this.right = this.components.SelectionBarRight = this.box.SelectionBarRight;
this.tp = this.components.TimePanel = this.box.TimePanel;
this.tpl = this.components.TimePanelLeft = this.tp.TimePanelLeft;
this.tpr = this.components.TimePanelRight = this.tp.TimePanelRight;
this.ctp = this.components.ControlTimePanel;
this.ctpl = this.components.ControlTimePanelLeft = this.ctp.ControlTimePanelLeft;
this.ctpr = this.components.ControlTimePanelRight = this.ctp.ControlTimePanelRight;
},
show: function () {
this.options.hidden = false;
if (typeof this.rstb != 'undefined') {
this.rstb.show();
if (this.options.controlTime)
this.showcontrolTime();
}
},
hide: function () {
this.options.hidden = true;
if (typeof this.rstb != 'undefined') {
this.rstb.hide();
this.ctp.hide();
}
},
showPanel: function () {
this.options.panel = true;
if (typeof this.tp != 'undefined')
videojsRemoveClass(this.tp.el_, 'disable');
},
showcontrolTime: function () {
this.options.controlTime = true;
if (typeof this.ctp != 'undefined')
this.ctp.show();
},
hidecontrolTime: function () {
this.options.controlTime = false;
if (typeof this.ctp != 'undefined')
this.ctp.hide();
},
setValue: function (index, seconds, writeControlTime) {
//index = 0 for the left Arrow and 1 for the right Arrow. Value in seconds
var writeControlTime = typeof writeControlTime != 'undefined' ? writeControlTime : true;
var percent = this._percent(seconds);
var isValidIndex = (index === 0 || index === 1);
var isChangeable = !this.locked;
if (isChangeable && isValidIndex)
this.box.setPosition(index, percent, writeControlTime);
},
setValues: function (start, end, writeControlTime) {
//index = 0 for the left Arrow and 1 for the right Arrow. Value in seconds
var writeControlTime = typeof writeControlTime != 'undefined' ? writeControlTime : true;
this._reset();
this._setValuesLocked(start, end, writeControlTime);
},
getValues: function () { //get values in seconds
var values = {}, start, end;
start = this.start || this._getArrowValue(0);
end = this.end || this._getArrowValue(1);
return {start: start, end: end};
},
_getArrowValue: function (index) {
var index = index || 0;
var duration = this.player.duration();
duration = typeof duration == 'undefined' ? 0 : duration;
var percentage = this[index === 0 ? "left" : "right"].el_.style.left.replace("%", "");
if (percentage == "")
percentage = index === 0 ? 0 : 100;
return videojsRound(this._seconds(percentage / 100), this.updatePrecision - 1);
},
_percent: function (seconds) {
var duration = this.player.duration();
if (isNaN(duration)) {
return 0;
}
return Math.min(1, Math.max(0, seconds / duration));
},
_seconds: function (percent) {
var duration = this.player.duration();
if (isNaN(duration)) {
return 0;
}
return Math.min(duration, Math.max(0, percent * duration));
},
_reset: function () {
var duration = this.player.duration();
this.tpl.el_.style.left = '0%';
this.tpr.el_.style.left = '100%';
this._setValuesLocked(0, duration);
},
_setValuesLocked: function (start, end, writeControlTime) {
var triggerSliderChange = typeof writeControlTime != 'undefined';
var writeControlTime = typeof writeControlTime != 'undefined' ? writeControlTime : true;
if (this.options.locked) {
this.unlock();//It is unlocked to change the bar position. In the end it will return the value.
this.setValue(0, start, writeControlTime);
this.setValue(1, end, writeControlTime);
this.lock();
} else {
this.setValue(0, start, writeControlTime);
this.setValue(1, end, writeControlTime);
}
// Trigger slider change
if (triggerSliderChange) {
this._triggerSliderChange();
}
},
_checkControlTime: function (index, TextInput, timeOld) {
var h = TextInput[0],
m = TextInput[1],
s = TextInput[2],
newHour = h.value,
newMin = m.value,
newSec = s.value,
obj, objNew, objOld;
index = index || 0;
if (newHour != timeOld[0]) {
obj = h;
objNew = newHour;
objOld = timeOld[0];
} else if (newMin != timeOld[1]) {
obj = m;
objNew = newMin;
objOld = timeOld[1];
} else if (newSec != timeOld[2]) {
obj = s;
objNew = newSec;
objOld = timeOld[2];
} else {
return false;
}
var duration = this.player.duration() || 0,
durationSel;
var intRegex = /^\d+$/;//check if the objNew is an integer
if (!intRegex.test(objNew) || objNew > 60) {
objNew = objNew == "" ? "" : objOld;
}
newHour = newHour == "" ? 0 : newHour;
newMin = newMin == "" ? 0 : newMin;
newSec = newSec == "" ? 0 : newSec;
durationSel = videojs.TextTrack.prototype.parseCueTime(newHour + ":" + newMin + ":" + newSec);
if (durationSel > duration) {
obj.value = objOld;
obj.style.border = "1px solid red";
} else {
obj.value = objNew;
h.style.border = m.style.border = s.style.border = "1px solid transparent";
this.setValue(index, durationSel, false);
// Trigger slider change
this._triggerSliderChange();
}
if (index === 1) {
var oldTimeLeft = this.ctpl.el_.children,
durationSelLeft = videojs.TextTrack.prototype.parseCueTime(oldTimeLeft[0].value + ":" + oldTimeLeft[1].value + ":" + oldTimeLeft[2].value);
if (durationSel < durationSelLeft) {
obj.style.border = "1px solid red";
}
} else {
var oldTimeRight = this.ctpr.el_.children,
durationSelRight = videojs.TextTrack.prototype.parseCueTime(oldTimeRight[0].value + ":" + oldTimeRight[1].value + ":" + oldTimeRight[2].value);
if (durationSel > durationSelRight) {
obj.style.border = "1px solid red";
}
}
},
_triggerSliderChange: function () {
this.player.trigger("sliderchange");
}
};
//----------------Public Functions----------------//
//-- Public Functions added to video-js
var videojsPlayer = videojs.getComponent('Player');
//Lock the Slider bar and it will not be possible to change the arrow positions
videojsPlayer.prototype.lockSlider = function () {
return this.rangeslider.lock();
};
//Unlock the Slider bar and it will be possible to change the arrow positions
videojsPlayer.prototype.unlockSlider = function () {
return this.rangeslider.unlock();
};
//Show the Slider Bar Component
videojsPlayer.prototype.showSlider = function () {
return this.rangeslider.show();
};
//Hide the Slider Bar Component
videojsPlayer.prototype.hideSlider = function () {
return this.rangeslider.hide();
};
//Show the Panel with the seconds of the selection
videojsPlayer.prototype.showSliderPanel = function () {
return this.rangeslider.showPanel();
};
//Hide the Panel with the seconds of the selection
videojsPlayer.prototype.hideSliderPanel = function () {
return this.rangeslider.hidePanel();
};
//Show the control Time to edit the position of the arrows
videojsPlayer.prototype.showControlTime = function () {
return this.rangeslider.showcontrolTime();
};
//Hide the control Time to edit the position of the arrows
videojsPlayer.prototype.hideControlTime = function () {
return this.rangeslider.hidecontrolTime();
};
//Set a Value in second for both arrows
videojsPlayer.prototype.setValueSlider = function (start, end) {
return this.rangeslider.setValues(start, end);
};
//The video will be played in a selected section
videojsPlayer.prototype.playBetween = function (start, end) {
return this.rangeslider.playBetween(start, end);
};
//The video will loop between to values
videojsPlayer.prototype.loopBetween = function (start, end) {
return this.rangeslider.loop(start, end);
};
//Set a Value in second for the arrows
videojsPlayer.prototype.getValueSlider = function () {
return this.rangeslider.getValues();
};
//----------------Create new Components----------------//
//--Charge the new Component into videojs
var videojsSeekBar = videojs.getComponent('SeekBar');
videojsSeekBar.prototype.options_.children.push('RSTimeBar'); //Range Slider Time Bar
var videojsControlBar = videojs.getComponent('ControlBar');
videojsControlBar.prototype.options_.children.push('ControlTimePanel'); //Panel with the time of the range slider
//-- Design the new components
var videojsComponent = videojs.getComponent('Component');
/**
* Range Slider Time Bar
* #param {videojs.Player|Object} player
* #param {Object=} options
* #constructor
*/
var videojsRSTimeBar = videojs.extend(videojsComponent, {
/** #constructor */
constructor: function (player, options) {
videojsComponent.call(this, player, options);
}
});
videojsRSTimeBar.prototype.init_ = function () {
this.rs = this.player_.rangeslider;
};
videojsRSTimeBar.prototype.options_ = {
children: {
'SeekRSBar': {}
}
};
videojsRSTimeBar.prototype.createEl = function () {
return videojsComponent.prototype.createEl.call(this, 'div', {
className: 'vjs-timebar-RS',
innerHTML: ''
});
};
videojs.registerComponent('RSTimeBar', videojsRSTimeBar);
/**
* Seek Range Slider Bar and holder for the selection bars
* #param {videojs.Player|Object} player
* #param {Object=} options
* #constructor
*/
var videojsSeekRSBar = videojs.extend(videojsSeekBar, {
/** #constructor */
constructor: function (player, options) {
videojsComponent.call(this, player, options);
this.on('mousedown', this.onMouseDown);
this.on('touchstart', this.onMouseDown);
}
});
videojsSeekRSBar.prototype.init_ = function () {
this.rs = this.player_.rangeslider;
};
videojsSeekRSBar.prototype.options_ = {
children: {
'SelectionBar': {},
'SelectionBarLeft': {},
'SelectionBarRight': {},
'TimePanel': {},
}
};
videojsSeekRSBar.prototype.createEl = function () {
return videojsComponent.prototype.createEl.call(this, 'div', {
className: 'vjs-rangeslider-holder'
});
};
videojsSeekRSBar.prototype.onMouseDown = function (event) {
event.preventDefault();
videojsBlockTextSelection();
if (!this.rs.options.locked) {
this.on(document, "mousemove", videojs.bind(this, this.onMouseMove));
this.on(document, "mouseup", videojs.bind(this, this.onMouseUp));
this.on(document, "touchmove", videojs.bind(this, this.onMouseMove));
this.on(document, "touchend", videojs.bind(this, this.onMouseUp));
}
};
videojsSeekRSBar.prototype.onMouseUp = function (event) {
this.off(document, "mousemove", videojs.bind(this, this.onMouseMove), false);
this.off(document, "mouseup", videojs.bind(this, this.onMouseUp), false);
this.off(document, "touchmove", videojs.bind(this, this.onMouseMove), false);
this.off(document, "touchend", videojs.bind(this, this.onMouseUp), false);
};
videojsSeekRSBar.prototype.onMouseMove = function (event) {
var left = this.calculateDistance(event);
if (this.rs.left.pressed)
this.setPosition(0, left);
else if (this.rs.right.pressed)
this.setPosition(1, left);
//Fix a problem with the presition in the display time
var ctd = this.player_.controlBar.currentTimeDisplay;
ctd.contentEl_.innerHTML = '<span class="vjs-control-text">' + ctd.localize('Current Time') + '</span>' + videojsFormatTime(this.rs._seconds(left), this.player_.duration());
// Trigger slider change
if (this.rs.left.pressed || this.rs.right.pressed) {
this.rs._triggerSliderChange();
}
};
videojsSeekRSBar.prototype.setPosition = function (index, left, writeControlTime) {
var writeControlTime = typeof writeControlTime != 'undefined' ? writeControlTime : true;
//index = 0 for left side, index = 1 for right side
var index = index || 0;
// Position shouldn't change when handle is locked
if (this.rs.options.locked)
return false;
// Check for invalid position
if (isNaN(left))
return false;
// Check index between 0 and 1
if (!(index === 0 || index === 1))
return false;
// Alias
var ObjLeft = this.rs.left.el_,
ObjRight = this.rs.right.el_,
Obj = this.rs[index === 0 ? 'left' : 'right'].el_,
tpr = this.rs.tpr.el_,
tpl = this.rs.tpl.el_,
bar = this.rs.bar,
ctp = this.rs[index === 0 ? 'ctpl' : 'ctpr'].el_;
//Check if left arrow is passing the right arrow
if ((index === 0 ? bar.updateLeft(left) : bar.updateRight(left))) {
Obj.style.left = (left * 100) + '%';
index === 0 ? bar.updateLeft(left) : bar.updateRight(left);
this.rs[index === 0 ? 'start' : 'end'] = this.rs._seconds(left);
//Fix the problem when you press the button and the two arrow are underhand
//left.zIndex = 10 and right.zIndex=20. This is always less in this case:
if (index === 0) {
if ((left) >= 0.9)
ObjLeft.style.zIndex = 25;
else
ObjLeft.style.zIndex = 10;
}
//-- Panel
var TimeText = videojsFormatTime(this.rs._seconds(left)),
tplTextLegth = tpl.children[0].innerHTML.length;
var MaxP, MinP, MaxDisP;
if (tplTextLegth <= 4) //0:00
MaxDisP = this.player_.isFullScreen ? 3.25 : 6.5;
else if (tplTextLegth <= 5)//00:00
MaxDisP = this.player_.isFullScreen ? 4 : 8;
else//0:00:00
MaxDisP = this.player_.isFullScreen ? 5 : 10;
if (TimeText.length <= 4) { //0:00
MaxP = this.player_.isFullScreen ? 97 : 93;
MinP = this.player_.isFullScreen ? 0.1 : 0.5;
} else if (TimeText.length <= 5) {//00:00
MaxP = this.player_.isFullScreen ? 96 : 92;
MinP = this.player_.isFullScreen ? 0.1 : 0.5;
} else {//0:00:00
MaxP = this.player_.isFullScreen ? 95 : 91;
MinP = this.player_.isFullScreen ? 0.1 : 0.5;
}
if (index === 0) {
tpl.style.left = Math.max(MinP, Math.min(MaxP, (left * 100 - MaxDisP / 2))) + '%';
if ((tpr.style.left.replace("%", "") - tpl.style.left.replace("%", "")) <= MaxDisP)
tpl.style.left = Math.max(MinP, Math.min(MaxP, tpr.style.left.replace("%", "") - MaxDisP)) + '%';
tpl.children[0].innerHTML = TimeText;
} else {
tpr.style.left = Math.max(MinP, Math.min(MaxP, (left * 100 - MaxDisP / 2))) + '%';
if (((tpr.style.left.replace("%", "") || 100) - tpl.style.left.replace("%", "")) <= MaxDisP)
tpr.style.left = Math.max(MinP, Math.min(MaxP, tpl.style.left.replace("%", "") - 0 + MaxDisP)) + '%';
tpr.children[0].innerHTML = TimeText;
}
//-- Control Time
if (writeControlTime) {
var time = TimeText.split(":"),
h, m, s;
if (time.length == 2) {
h = 0;
m = time[0];
s = time[1];
} else {
h = time[0];
m = time[1];
s = time[2];
}
ctp.children[0].value = h;
ctp.children[1].value = m;
ctp.children[2].value = s;
}
}
return true;
};
videojs.registerComponent('SeekRSBar', videojsSeekRSBar);
/**
* This is the bar with the selection of the RangeSlider
* #param {videojs.Player|Object} player
* #param {Object=} options
* #constructor
*/
var videojsSelectionBar = videojs.extend(videojsComponent, {
/** #constructor */
constructor: function (player, options) {
videojsComponent.call(this, player, options);
this.on('mouseup', this.onMouseUp);
this.on('touchend', this.onMouseUp);
this.fired = false;
}
});
videojsSelectionBar.prototype.init_ = function () {
this.rs = this.player_.rangeslider;
};
videojsSelectionBar.prototype.createEl = function () {
return videojsComponent.prototype.createEl.call(this, 'div', {
className: 'vjs-selectionbar-RS'
});
};
videojsControlTimePanelRight.prototype.init_ = function () {
this.rs = this.player_.rangeslider;
this.timeOld = {};
};
videojsControlTimePanelRight.prototype.createEl = function () {
return videojsComponent.prototype.createEl.call(this, 'div', {
className: 'vjs-controltimepanel-right-RS',
innerHTML: 'End: <input type="text" id="controltimepanel" maxlength="2" value="00"/>:<input type="text" id="controltimepanel" maxlength="2" value="00"/>:<input type="text" id="controltimepanel" maxlength="2" value="00"/>'
});
};
videojsControlTimePanelRight.prototype.onKeyDown = function (event) {
this.timeOld[0] = this.el_.children[0].value;
this.timeOld[1] = this.el_.children[1].value;
this.timeOld[2] = this.el_.children[2].value;
};
videojsControlTimePanelRight.prototype.onKeyUp = function (event) {
this.rs._checkControlTime(1, this.el_.children, this.timeOld);
};
videojs.registerComponent('ControlTimePanelRight', videojsControlTimePanelRight);
})();
And this is how rangeslider looks everytime it shows up
I use
video.currentTime
But it looks like rangeslider is using
e.currentPoint
I know very little about Javascript but need to use hammer.js in a project I'm working on.
Instead of replacing/refreshing the image im trying to use the pull to refresh scrit to refresh the page.
Ive tried adding
location.reload();
to the script but to no avail, can anyone shed any light on this.
http://eightmedia.github.io/hammer.js/
This is the code im using
/**
* requestAnimationFrame and cancel polyfill
*/
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
/**
* pull to refresh
* #type {*}
*/
var PullToRefresh = (function() {
function Main(container, slidebox, slidebox_icon, handler) {
var self = this;
this.breakpoint = 80;
this.container = container;
this.slidebox = slidebox;
this.slidebox_icon = slidebox_icon;
this.handler = handler;
this._slidedown_height = 0;
this._anim = null;
this._dragged_down = false;
this.hammertime = Hammer(this.container)
.on("touch dragdown release", function(ev) {
self.handleHammer(ev);
});
};
/**
* Handle HammerJS callback
* #param ev
*/
Main.prototype.handleHammer = function(ev) {
var self = this;
switch(ev.type) {
// reset element on start
case 'touch':
this.hide();
break;
// on release we check how far we dragged
case 'release':
if(!this._dragged_down) {
return;
}
// cancel animation
cancelAnimationFrame(this._anim);
// over the breakpoint, trigger the callback
if(ev.gesture.deltaY >= this.breakpoint) {
container_el.className = 'pullrefresh-loading';
pullrefresh_icon_el.className = 'icon loading';
this.setHeight(60);
this.handler.call(this);
}
// just hide it
else {
pullrefresh_el.className = 'slideup';
container_el.className = 'pullrefresh-slideup';
this.hide();
}
break;
// when we dragdown
case 'dragdown':
this._dragged_down = true;
// if we are not at the top move down
var scrollY = window.scrollY;
if(scrollY > 5) {
return;
} else if(scrollY !== 0) {
window.scrollTo(0,0);
}
// no requestAnimationFrame instance is running, start one
if(!this._anim) {
this.updateHeight();
}
// stop browser scrolling
ev.gesture.preventDefault();
// update slidedown height
// it will be updated when requestAnimationFrame is called
this._slidedown_height = ev.gesture.deltaY * 0.4;
break;
}
};
/**
* when we set the height, we just change the container y
* #param {Number} height
*/
Main.prototype.setHeight = function(height) {
if(Modernizr.csstransforms3d) {
this.container.style.transform = 'translate3d(0,'+height+'px,0) ';
this.container.style.oTransform = 'translate3d(0,'+height+'px,0)';
this.container.style.msTransform = 'translate3d(0,'+height+'px,0)';
this.container.style.mozTransform = 'translate3d(0,'+height+'px,0)';
this.container.style.webkitTransform = 'translate3d(0,'+height+'px,0) scale3d(1,1,1)';
}
else if(Modernizr.csstransforms) {
this.container.style.transform = 'translate(0,'+height+'px) ';
this.container.style.oTransform = 'translate(0,'+height+'px)';
this.container.style.msTransform = 'translate(0,'+height+'px)';
this.container.style.mozTransform = 'translate(0,'+height+'px)';
this.container.style.webkitTransform = 'translate(0,'+height+'px)';
}
else {
this.container.style.top = height+"px";
}
};
/**
* hide the pullrefresh message and reset the vars
*/
Main.prototype.hide = function() {
container_el.className = '';
this._slidedown_height = 0;
this.setHeight(0);
cancelAnimationFrame(this._anim);
this._anim = null;
this._dragged_down = false;
};
/**
* hide the pullrefresh message and reset the vars
*/
Main.prototype.slideUp = function() {
var self = this;
cancelAnimationFrame(this._anim);
pullrefresh_el.className = 'slideup';
container_el.className = 'pullrefresh-slideup';
this.setHeight(0);
setTimeout(function() {
self.hide();
}, 500);
};
/**
* update the height of the slidedown message
*/
Main.prototype.updateHeight = function() {
var self = this;
this.setHeight(this._slidedown_height);
if(this._slidedown_height >= this.breakpoint){
this.slidebox.className = 'breakpoint';
this.slidebox_icon.className = 'icon arrow arrow-up';
}
else {
this.slidebox.className = '';
this.slidebox_icon.className = 'icon arrow';
}
this._anim = requestAnimationFrame(function() {
self.updateHeight();
});
};
return Main;
})();
function getEl(id) {
return document.getElementById(id);
}
var container_el = getEl('container');
var pullrefresh_el = getEl('pullrefresh');
var pullrefresh_icon_el = getEl('pullrefresh-icon');
var image_el = getEl('random-image');
var refresh = new PullToRefresh(container_el, pullrefresh_el, pullrefresh_icon_el);
// update image onrefresh
refresh.handler = function() {
var self = this;
// a small timeout to demo the loading state
setTimeout(function() {
var preload = new Image();
preload.onload = function() {
image_el.src = this.src;
self.slideUp();
};
preload.src = 'http://lorempixel.com/800/600/?'+ (new Date().getTime());
}, 1000);
};
There is a Beer involved for anyone that can fix this :)
http://jsfiddle.net/zegermens/PDcr9/1/
You're assigning the return value of the location.reload function to the src attribute of an Image element. I'm not sure if the function even has a return value, https://developer.mozilla.org/en-US/docs/Web/API/Location.reload
Try this:
// update image onrefresh
refresh.handler = function() {
var self = this;
// a small timeout to demo the loading state
setTimeout(function() {
window.location.reload();
}, 1000);
};
I am trying to implement column resizing using jQuery like below(Please see http://jsbin.com/uduNUbo/1/edit)
Here is my JS code
function resizeEvents(selector) {
function XY(e, ele) {
var parentOffset = ele.parent().offset();
return e.pageX - parentOffset.left;
}
var checkPos;
$(selector).on('mousedown', function () {
$(this).attr('init', true);
return false;
});
$(selector).on('mouseup', function () {
$(this).attr('init', false);
});
$(selector).closest('div').on('mousemove', function (e) {
var inits = $(this).find('.resize').filter(function(){
return $(this).attr('init') == true;
});
if (inits.length > 0) {
var pos = XY(e, inits.first());
if (!checkPos) {
checkPos = pos;
return false;
} else {
var moved = checkPos - pos, a = moved > 0 ? 1 : -1 ;
th.prevAll().each(function () {
if (!$(this).hasClass('.resize')) {
$(this).width($(this).width() + a);
}
});
th.nextAll().each(function () {
if (!$(this).hasClass('.resize')) {
$(this).width($(this).width() - a);
}
});
}
}
});
}
resizeEvents('.resize');
But this is not working, My Question is Is mousemove is written properly, to define properly on correct element or not.
I fixed the code for you:
function resizeEvents(selector) {
var selected;
$(selector).on('mousedown', function () {
selected = $(this);
return false;
});
$(document).mouseup(function () {
selected = null;
}).mousemove(function(e) {
var target = $(e.target);
var table = target.parents('.table');
if (table.length && selected) {
var x = e.pageX - table.offset().left;
var splitter_x = selected.offset().left;
var prev = selected.prev();
var next = selected.next();
prev.width(prev.width() + (x - splitter_x));
next.width(next.width() - (x - splitter_x));
}
});
}
http://jsbin.com/uduNUbo/5/edit
This is a script that is generated by CodeCharge (code generator) as part of my app (well, also by Artisteer designs, apparently). I have very little knowledge of web development, zero knowledge of JS and I have to use this code generator. The script keeps coming up with this error: "Line: 139, Char: 13, Error: Unable to get property 'parent' of undefined or null reference, Code:0, URL: ). Like I was saying, I have no control upon generation of this script, but I can go and modify it, to hopefully fix this. Below is the full script. Line 139 is:
var s = c.parent().children('.art-layout-cell:not(.art-content)');
This is full script:
/* begin Page */
/* Created by Artisteer v3.1.0.55575 */
// css helper
(function($) {
var data = [
{str:navigator.userAgent,sub:'Chrome',ver:'Chrome',name:'chrome'},
{str:navigator.vendor,sub:'Apple',ver:'Version',name:'safari'},
{prop:window.opera,ver:'Opera',name:'opera'},
{str:navigator.userAgent,sub:'Firefox',ver:'Firefox',name:'firefox'},
{str:navigator.userAgent,sub:'MSIE',ver:'MSIE',name:'ie'}];
for (var n=0;n<data.length;n++) {
if ((data[n].str && (data[n].str.indexOf(data[n].sub) != -1)) || data[n].prop) {
var v = function(s){var i=s.indexOf(data[n].ver);return (i!=-1)? parseInt(s.substring(i+data[n].ver.length+1)):'';};
$('html').addClass(data[n].name+' '+data[n].name+v(navigator.userAgent) || v(navigator.appVersion)); break;
}
}
})(jQuery);
/* end Page */
/* begin Menu */
jQuery(function () {
if (!jQuery.browser.msie || parseInt(jQuery.browser.version) > 7) return;
jQuery('ul.art-hmenu>li:not(:first-child)').each(function () { jQuery(this).prepend('<span class="art-hmenu-separator"> </span>'); });
if (!jQuery.browser.msie || parseInt(jQuery.browser.version) > 6) return;
jQuery('ul.art-hmenu li').each(function () {
this.j = jQuery(this);
this.UL = this.j.children('ul:first');
if (this.UL.length == 0) return;
this.A = this.j.children('a:first');
this.onmouseenter = function () {
this.j.addClass('art-hmenuhover');
this.UL.addClass('art-hmenuhoverUL');
this.A.addClass('art-hmenuhoverA');
};
this.onmouseleave = function() {
this.j.removeClass('art-hmenuhover');
this.UL.removeClass('art-hmenuhoverUL');
this.A.removeClass('art-hmenuhoverA');
};
});
});
jQuery(function() { setHMenuOpenDirection({container: "div.art-sheet-body", defaultContainer: "#art-main", menuClass: "art-hmenu", leftToRightClass: "art-hmenu-left-to-right", rightToLeftClass: "art-hmenu-right-to-left"}); });
function setHMenuOpenDirection(menuInfo) {
var defaultContainer = jQuery(menuInfo.defaultContainer);
defaultContainer = defaultContainer.length > 0 ? defaultContainer = jQuery(defaultContainer[0]) : null;
jQuery("ul." + menuInfo.menuClass + ">li>ul").each(function () {
var submenu = jQuery(this);
var submenuWidth = submenu.outerWidth();
var submenuLeft = submenu.offset().left;
var mainContainer = submenu.parents(menuInfo.container);
mainContainer = mainContainer.length > 0 ? mainContainer = jQuery(mainContainer[0]) : null;
var container = mainContainer || defaultContainer;
if (container != null) {
var containerLeft = container.offset().left;
var containerWidth = container.outerWidth();
if (submenuLeft + submenuWidth >=
containerLeft + containerWidth)
/* right to left */
submenu.addClass(menuInfo.rightToLeftClass).find("ul").addClass (menuInfo.rightToLeftClass);
if (submenuLeft <= containerLeft)
/* left to right */
submenu.addClass(menuInfo.leftToRightClass).find("ul").addClass (menuInfo.leftToRightClass);
}
});
}
jQuery(function ($) {
$("ul.art-hmenu a:not([href])").attr('href', '#').click(function (e) { e.preventDefault(); });
});
/* end Menu */
/* begin MenuSubItem */
jQuery(function () {
jQuery("ul.art-hmenu ul li").hover(function () { jQuery(this).prev().children("a").addClass("art-hmenu-before-hovered"); },
function () { jQuery(this).prev().children("a").removeClass("art-hmenu-before-hovered"); });
});
jQuery(function () {
if (!jQuery.browser.msie) return;
var ieVersion = parseInt(jQuery.browser.version);
if (ieVersion > 7) return;
/* Fix width of submenu items.
* The width of submenu item calculated incorrectly in IE6-7. IE6 has wider items, IE7 display items like stairs.
*/
jQuery.each(jQuery("ul.art-hmenu ul"), function () {
var maxSubitemWidth = 0;
var submenu = jQuery(this);
var subitem = null;
jQuery.each(submenu.children("li").children("a"), function () {
subitem = jQuery(this);
var subitemWidth = subitem.outerWidth();
if (maxSubitemWidth < subitemWidth)
maxSubitemWidth = subitemWidth;
});
if (subitem != null) {
var subitemBorderLeft = parseInt(subitem.css("border-left-width"), 10) || 0;
var subitemBorderRight = parseInt(subitem.css("border-right-width"), 10) || 0;
var subitemPaddingLeft = parseInt(subitem.css("padding-left"), 10) || 0;
var subitemPaddingRight = parseInt(subitem.css("padding-right"), 10) || 0;
maxSubitemWidth -= subitemBorderLeft + subitemBorderRight + subitemPaddingLeft + subitemPaddingRight;
submenu.children("li").children("a").css("width", maxSubitemWidth + "px");
}
});
if (ieVersion > 6) return;
jQuery("ul.art-hmenu ul>li:first-child>a").css("border-top-width", "1px");
});
/* end MenuSubItem */
/* begin Layout */
jQuery(function () {
jQuery(window).bind('resize', function () {
var bh = jQuery('body').height();
var mh = 0;
jQuery('#art-main').children().each(function() {
if (jQuery(this).css('position') != 'absolute')
mh += jQuery(this).outerHeight(true);
});
if (mh < bh)
{
var r = bh - mh;
var c = jQuery('div.art-content');
c.css('height', (c.outerHeight(true) + r) + 'px');
}
});
if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 8) {
jQuery(window).bind('resize', function() {
var c = $('div.art-content');
var s = c.parent().children('.art-layout-cell:not(.art-content)');
var w = 0;
c.hide();
s.each(function() { w += this.clientWidth; });
c.w = c.parent().width(); c.css('width', c.w - w + 'px');
c.show();
});
}
jQuery(window).trigger('resize');
});
/* end Layout */
/* begin Button */
function artButtonSetup(className) {
jQuery.each(jQuery("a." + className + ", button." + className + ", input." + className), function (i, val) {
var b = jQuery(val);
if (!b.parent().hasClass('art-button-wrapper')) {
if (b.is('input')) b.val(b.val().replace(/^\s*/, '')).css('zoom', '1');
if (!b.hasClass('art-button')) b.addClass('art-button');
jQuery("<span class='art-button-wrapper'><span class='art-button-l'> </span><span class='art-button-r'> </span></span>").insertBefore(b).append(b);
if (b.hasClass('active')) b.parent().addClass('active');
}
b.mouseover(function () { jQuery(this).parent().addClass("hover"); });
b.mouseout(function () { var b = jQuery(this); b.parent().removeClass("hover"); if (!b.hasClass('active')) b.parent().removeClass('active'); });
b.mousedown(function () { var b = jQuery(this); b.parent().removeClass("hover"); if (!b.hasClass('active')) b.parent().addClass('active'); });
b.mouseup(function () { var b = jQuery(this); if (!b.hasClass('active')) b.parent().removeClass('active'); });
});
}
jQuery(function() { artButtonSetup("art-button"); });
/* end Button */
// adds spans to apply css styles for buttons with class "Button"
jQuery(function() { artButtonSetup("Button"); });
jQuery(function() {
// events for CCS AjaxPanel can be set with help of AjaxPanelEvents
if (typeof window.AjaxPanelEvents == "undefined") window.AjaxPanelEvents = [];
// when CCS AjaxPanel is updated the buttons should be decorated with spans again
window.AjaxPanelEvents.push({
eventName: "afterUpdate",
func: function(updatePanel) {
// adds spans to apply css styles for buttons with class "Button"
artButtonSetup("Button", updatePanel);
// adds spans to apply css styles for buttons with class "art-button"
artButtonSetup("art-button", updatePanel);
}
});
});
Can anybody help? Thanks!
It seems that c is not instantiated, something like c = new anything.
It looks like you might have used jQuery.noConflit() in your project, so $ is not jQuery object.
So change
var c = $('div.art-content');
to
var c = jQuery('div.art-content');