Global variable in jQuery plugin - javascript

Ok guys I've been working on a sort of slider for JQtouch and I have two methods in my plugin, one that builds the slider on initiation and one that rebuilds it on rotation. I use a variable called "count" that holds the number of the current slide. My issue is, I lose the variable when ever the mobile device is rotated and the "rotate" method is called.
I defined the count variable in my settings as "1" and it seems that when the rotate method is called it takes the default set "1" instead of the current slide number. Here's my plugin code; it's very long. Basically everything that is happening in my init: method, all of the swiping and sliding changing of the "count" variable doesn't carry over to the "rotate" method.
(function ($) {
var empty = {};
var settings = {
count: 1,
};
var methods = {
init: function (options, callback, defaults) {
var options = $.extend({},
settings, options || {});
return this.each(function () {
var $this = $(this);
if (options.height) {
mHeight = options.height;
} else {
mHeight = $(window).height();
}
mWidth = $(window).width();
mAmount = $('.swiper', this).length;
amount = $('.swiper', this).length;
holdWidth = mWidth * options.amount;
$('.swiper', this).height(mHeight);
$(this).height(mHeight);
$('.swiper', this).width(mWidth);
$(this).width(holdWidth);
$('.swipe_slide', this).width(holdWidth);
$('.swipe_slide', this).height(mHeight);
$('.swiper', this).each(function (i) {
var nwidth = mWidth * i;
$(this).css('left', nwidth);
});
$('.swipe_slide', this).swipe(function (evt, data) {
var amount = $('.swiper', this).length; // alert($($this).attr('id'));
if (data.direction == 'left') { //alert('count: '+options.count+" amount: "+options.amount);
if (options.count != amount) {
moveWidth = options.count * -mWidth;
$('.swipe_slide', $this).css("left", moveWidth);
options.count++
} else {
return
}
} else {
if (options.count != 1) {
moveWidth = moveWidth + mWidth;
$('.swipe_slide', $this).css("left", moveWidth);
options.count--
} else {
return
}
}
});
});
},
rotate: function (options, callback, defaults) {
var $this = $(this);
var options = $.extend({},
settings, options || {});
alert(options.count);
return this.each(function () {
if (options.height) {
mHeight = options.height;
} else {
mHeight = $(window).height();
}
mWidth = $(window).width();
mAmount = $('.swiper', this).length;
amount = $('.swiper', this).length;
holdWidth = mWidth * mAmount;
$('.swiper', this).height(mHeight);
$(this).height(mHeight);
$('.swipe_slide', this).height(mHeight);
$('.swiper', this).width(mWidth);
$(this).width(holdWidth);
$('.swipe_slide', this).width(holdWidth);
$('.swiper', this).each(function (i) {
var nwidth = mWidth * i;
$(this).css('left', nwidth);
});
newMoveWidth = options.count * $(window).width();
alert(options.count);
alert(newMoveWidth); //$('.swipe_slide',$this).css( "left" , 0 );
});
}
}
$.fn.jCarousel = function (method, options) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.jModalbox');
}
};
})(jQuery);

If I followed this, your problem is you're changing the value of count in the extended options, a local variable. These changes won't propagate back up to settings like you think unless you pass settings as the target. That might not be exactly what you want, but I'm pretty sure it should get you headed in the right direction:
http://jsfiddle.net/DTnW8/

Related

How to avoid collapse menubar and cover carousel in website?

first of all im sorry for taking your time. I used album cover slider and superfish in my first site and they collapsed. I can use slider perfectly but i cant use my menu. Submenus and everything shows when i take my cursor to there. I want to learn how to avoid click collapse in js projects, little explanation would help me big time.
Here are the JS's.
for menu
* jQuery Superfish Menu Plugin - v1.7.9
* Copyright (c) 2016 Joel Birch
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
;(function ($, w) {
"use strict";
var methods = (function () {
// private properties and methods go here
var c = {
bcClass: 'sf-breadcrumb',
menuClass: 'sf-js-enabled',
anchorClass: 'sf-with-ul',
menuArrowClass: 'sf-arrows'
},
ios = (function () {
var ios = /^(?![\w\W]*Windows Phone)[\w\W]*(iPhone|iPad|iPod)/i.test(navigator.userAgent);
if (ios) {
// tap anywhere on iOS to unfocus a submenu
$('html').css('cursor', 'pointer').on('click', $.noop);
}
return ios;
})(),
wp7 = (function () {
var style = document.documentElement.style;
return ('behavior' in style && 'fill' in style && /iemobile/i.test(navigator.userAgent));
})(),
unprefixedPointerEvents = (function () {
return (!!w.PointerEvent);
})(),
toggleMenuClasses = function ($menu, o, add) {
var classes = c.menuClass,
method;
if (o.cssArrows) {
classes += ' ' + c.menuArrowClass;
}
method = (add) ? 'addClass' : 'removeClass';
$menu[method](classes);
},
setPathToCurrent = function ($menu, o) {
return $menu.find('li.' + o.pathClass).slice(0, o.pathLevels)
.addClass(o.hoverClass + ' ' + c.bcClass)
.filter(function () {
return ($(this).children(o.popUpSelector).hide().show().length);
}).removeClass(o.pathClass);
},
toggleAnchorClass = function ($li, add) {
var method = (add) ? 'addClass' : 'removeClass';
$li.children('a')[method](c.anchorClass);
},
toggleTouchAction = function ($menu) {
var msTouchAction = $menu.css('ms-touch-action');
var touchAction = $menu.css('touch-action');
touchAction = touchAction || msTouchAction;
touchAction = (touchAction === 'pan-y') ? 'auto' : 'pan-y';
$menu.css({
'ms-touch-action': touchAction,
'touch-action': touchAction
});
},
getMenu = function ($el) {
return $el.closest('.' + c.menuClass);
},
getOptions = function ($el) {
return getMenu($el).data('sfOptions');
},
over = function () {
var $this = $(this),
o = getOptions($this);
clearTimeout(o.sfTimer);
$this.siblings().superfish('hide').end().superfish('show');
},
close = function (o) {
o.retainPath = ($.inArray(this[0], o.$path) > -1);
this.superfish('hide');
if (!this.parents('.' + o.hoverClass).length) {
o.onIdle.call(getMenu(this));
if (o.$path.length) {
$.proxy(over, o.$path)();
}
}
},
out = function () {
var $this = $(this),
o = getOptions($this);
if (ios) {
$.proxy(close, $this, o)();
}
else {
clearTimeout(o.sfTimer);
o.sfTimer = setTimeout($.proxy(close, $this, o), o.delay);
}
},
touchHandler = function (e) {
var $this = $(this),
o = getOptions($this),
$ul = $this.siblings(e.data.popUpSelector);
if (o.onHandleTouch.call($ul) === false) {
return this;
}
if ($ul.length > 0 && $ul.is(':hidden')) {
$this.one('click.superfish', false);
if (e.type === 'MSPointerDown' || e.type === 'pointerdown') {
$this.trigger('focus');
} else {
$.proxy(over, $this.parent('li'))();
}
}
},
applyHandlers = function ($menu, o) {
var targets = 'li:has(' + o.popUpSelector + ')';
if ($.fn.hoverIntent && !o.disableHI) {
$menu.hoverIntent(over, out, targets);
}
else {
$menu
.on('mouseenter.superfish', targets, over)
.on('mouseleave.superfish', targets, out);
}
var touchevent = 'MSPointerDown.superfish';
if (unprefixedPointerEvents) {
touchevent = 'pointerdown.superfish';
}
if (!ios) {
touchevent += ' touchend.superfish';
}
if (wp7) {
touchevent += ' mousedown.superfish';
}
$menu
.on('focusin.superfish', 'li', over)
.on('focusout.superfish', 'li', out)
.on(touchevent, 'a', o, touchHandler);
};
return {
// public methods
hide: function (instant) {
if (this.length) {
var $this = this,
o = getOptions($this);
if (!o) {
return this;
}
var not = (o.retainPath === true) ? o.$path : '',
$ul = $this.find('li.' + o.hoverClass).add(this).not(not).removeClass(o.hoverClass).children(o.popUpSelector),
speed = o.speedOut;
if (instant) {
$ul.show();
speed = 0;
}
o.retainPath = false;
if (o.onBeforeHide.call($ul) === false) {
return this;
}
$ul.stop(true, true).animate(o.animationOut, speed, function () {
var $this = $(this);
o.onHide.call($this);
});
}
return this;
},
show: function () {
var o = getOptions(this);
if (!o) {
return this;
}
var $this = this.addClass(o.hoverClass),
$ul = $this.children(o.popUpSelector);
if (o.onBeforeShow.call($ul) === false) {
return this;
}
$ul.stop(true, true).animate(o.animation, o.speed, function () {
o.onShow.call($ul);
});
return this;
},
destroy: function () {
return this.each(function () {
var $this = $(this),
o = $this.data('sfOptions'),
$hasPopUp;
if (!o) {
return false;
}
$hasPopUp = $this.find(o.popUpSelector).parent('li');
clearTimeout(o.sfTimer);
toggleMenuClasses($this, o);
toggleAnchorClass($hasPopUp);
toggleTouchAction($this);
// remove event handlers
$this.off('.superfish').off('.hoverIntent');
// clear animation's inline display style
$hasPopUp.children(o.popUpSelector).attr('style', function (i, style) {
return style.replace(/display[^;]+;?/g, '');
});
// reset 'current' path classes
o.$path.removeClass(o.hoverClass + ' ' + c.bcClass).addClass(o.pathClass);
$this.find('.' + o.hoverClass).removeClass(o.hoverClass);
o.onDestroy.call($this);
$this.removeData('sfOptions');
});
},
init: function (op) {
return this.each(function () {
var $this = $(this);
if ($this.data('sfOptions')) {
return false;
}
var o = $.extend({}, $.fn.superfish.defaults, op),
$hasPopUp = $this.find(o.popUpSelector).parent('li');
o.$path = setPathToCurrent($this, o);
$this.data('sfOptions', o);
toggleMenuClasses($this, o, true);
toggleAnchorClass($hasPopUp, true);
toggleTouchAction($this);
applyHandlers($this, o);
$hasPopUp.not('.' + c.bcClass).superfish('hide', true);
o.onInit.call(this);
});
}
};
})();
$.fn.superfish = function (method, args) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
}
else {
return $.error('Method ' + method + ' does not exist on jQuery.fn.superfish');
}
};
$.fn.superfish.defaults = {
popUpSelector: 'ul,.sf-mega', // within menu context
hoverClass: 'sfHover',
pathClass: 'overrideThisToUse',
pathLevels: 1,
delay: 800,
animation: {opacity: 'show'},
animationOut: {opacity: 'hide'},
speed: 'normal',
speedOut: 'fast',
cssArrows: true,
disableHI: false,
onInit: $.noop,
onBeforeShow: $.noop,
onShow: $.noop,
onBeforeHide: $.noop,
onHide: $.noop,
onIdle: $.noop,
onDestroy: $.noop,
onHandleTouch: $.noop
};
})(jQuery, window);
Album Cover Slider
--------------------------------*/
//start added by Chase
var a = document.getElementsByTagName("a");
var cfImg = document.getElementsByClassName("coverflow__image")
var scaleI = 0;
for (scaleI; scaleI < a.length; scaleI++) {
if (scaleI === 3) {
continue;
} else {
a[scaleI].style.cursor = "default";
a[scaleI].addEventListener("click", prevDef);
}
}
function prevDef(e) {
e.preventDefault();
}
function forScale(coverflowPos) {
for (scaleI = 0; scaleI < a.length; scaleI++) {
a[scaleI].style.cursor = "default";
a[scaleI].addEventListener("click", prevDef);
}
for (scaleI = 0; scaleI < cfImg.length; scaleI++) {
if (cfImg[scaleI].getAttribute("data-coverflow-index") == coverflowPos) {
cfImg[scaleI].parentElement.style.cursor = "pointer";
cfImg[scaleI].parentElement.removeEventListener("click", prevDef);
}
}
}
//end added by Chase
function setupCoverflow(coverflowContainer) {
var coverflowContainers;
if (typeof coverflowContainer !== "undefined") {
if (Array.isArray(coverflowContainer)) {
coverflowContainers = coverflowContainer;
} else {
coverflowContainers = [coverflowContainer];
}
} else {
coverflowContainers = Array.prototype.slice.apply(document.getElementsByClassName('coverflow'));
}
coverflowContainers.forEach(function(containerElement) {
var coverflow = {};
var prevArrows, nextArrows;
//capture coverflow elements
coverflow.container = containerElement;
coverflow.images = Array.prototype.slice.apply(containerElement.getElementsByClassName('coverflow__image'));
coverflow.position = Math.floor(coverflow.images.length / 2) + 1;
//set indicies on images
coverflow.images.forEach(function(coverflowImage, i) {
coverflowImage.dataset.coverflowIndex = i + 1;
});
//set initial position
coverflow.container.dataset.coverflowPosition = coverflow.position;
//get prev/next arrows
prevArrows = Array.prototype.slice.apply(coverflow.container.getElementsByClassName("prev-arrow"));
nextArrows = Array.prototype.slice.apply(coverflow.container.getElementsByClassName("next-arrow"));
//add event handlers
function setPrevImage() {
coverflow.position = Math.max(1, coverflow.position - 1);
coverflow.container.dataset.coverflowPosition = coverflow.position;
//call the functin forScale added
forScale(coverflow.position);
}
function setNextImage() {
coverflow.position = Math.min(coverflow.images.length, coverflow.position + 1);
coverflow.container.dataset.coverflowPosition = coverflow.position;
//call the function Chase added
forScale(coverflow.position);
}
function jumpToImage(evt) {
coverflow.position = Math.min(coverflow.images.length, Math.max(1, evt.target.dataset.coverflowIndex));
coverflow.container.dataset.coverflowPosition = coverflow.position;
//start added by Chase
setTimeout(function() {
forScale(coverflow.position);
}, 1);
//end added by Chase
}
function onKeyPress(evt) {
switch (evt.which) {
case 37: //left arrow
setPrevImage();
break;
case 39: //right arrow
setNextImage();
break;
}
}
prevArrows.forEach(function(prevArrow) {
prevArrow.addEventListener('click', setPrevImage);
});
nextArrows.forEach(function(nextArrow) {
nextArrow.addEventListener('click', setNextImage);
});
coverflow.images.forEach(function(image) {
image.addEventListener('click', jumpToImage);
});
window.addEventListener('keyup', onKeyPress);
});
}
setupCoverflow(); ```

when click on button the time is count and show totall time

hi gyzz i am new in jquery , when i click add button the running time is count suddenly when i click add button and its count , i click 3 times and its count different time and when i click totall button then show total time that i click 3 times add 3 different time , how this is possible... i use simple stopwatch plugin..
my code is
(function( $ ){
//my code
$('#demo1').stopwatch().stopwatch('start');
//count time indually
$(".add_time").click(function(e) {
e.preventDefault();
var time_record = $('.example').find('#timer').text();
var time_record++;
console.log(time_record);
});
//get totall time
$(".totall_time").click(function(e) {
e.preventDefault();
});
//stopwatch plugin
function incrementer(ct, increment) {
return function() { ct+=increment; return ct; };
}
function pad2(number) {
return (number < 10 ? '0' : '') + number;
}
function defaultFormatMilliseconds(millis) {
var x, seconds, minutes, hours;
x = millis / 1000;
seconds = Math.floor(x % 60);
x /= 60;
minutes = Math.floor(x % 60);
x /= 60;
// hours = Math.floor(x % 24);
// x /= 24;
// days = Math.floor(x);
return [pad2(minutes), pad2(seconds)].join(':');
}
//NOTE: This is a the 'lazy func def' pattern described at http://michaux.ca/articles/lazy-function-definition-pattern
function formatMilliseconds(millis, data) {
// Use jintervals if available, else default formatter
var formatter;
if (typeof jintervals == 'function') {
formatter = function(millis, data){return jintervals(millis/1000, data.format);};
} else {
formatter = defaultFormatMilliseconds;
}
formatMilliseconds = function(millis, data) {
return formatter(millis, data);
};
return formatMilliseconds(millis, data);
}
var methods = {
init: function(options) {
var defaults = {
updateInterval: 1000,
startTime: 0,
format: '{HH}:{MM}:{SS}',
formatter: formatMilliseconds
};
// if (options) { $.extend(settings, options); }
return this.each(function() {
var $this = $(this),
data = $this.data('stopwatch');
// If the plugin hasn't been initialized yet
if (!data) {
// Setup the stopwatch data
var settings = $.extend({}, defaults, options);
data = settings;
data.active = false;
data.target = $this;
data.elapsed = settings.startTime;
// create counter
data.incrementer = incrementer(data.startTime, data.updateInterval);
data.tick_function = function() {
var millis = data.incrementer();
data.elapsed = millis;
data.target.trigger('tick.stopwatch', [millis]);
data.target.stopwatch('render');
};
$this.data('stopwatch', data);
}
});
},
start: function() {
return this.each(function() {
var $this = $(this),
data = $this.data('stopwatch');
// Mark as active
data.active = true;
data.timerID = setInterval(data.tick_function, data.updateInterval);
$this.data('stopwatch', data);
});
},
stop: function() {
return this.each(function() {
var $this = $(this),
data = $this.data('stopwatch');
clearInterval(data.timerID);
data.active = false;
$this.data('stopwatch', data);
});
},
destroy: function() {
return this.each(function(){
var $this = $(this),
data = $this.data('stopwatch');
$this.stopwatch('stop').unbind('.stopwatch').removeData('stopwatch');
});
},
render: function() {
var $this = $(this),
data = $this.data('stopwatch');
$this.html(data.formatter(data.elapsed, data));
},
getTime: function() {
var $this = $(this),
data = $this.data('stopwatch');
return data.elapsed;
},
toggle: function() {
return this.each(function() {
var $this = $(this);
var data = $this.data('stopwatch');
if (data.active) {
$this.stopwatch('stop');
} else {
$this.stopwatch('start');
}
});
},
reset: function() {
return this.each(function() {
var $this = $(this);
data = $this.data('stopwatch');
data.incrementer = incrementer(data.startTime, data.updateInterval);
data.elapsed = data.startTime;
$this.data('stopwatch', data);
});
}
};
// Define the function
$.fn.stopwatch = function( method ) {
if (methods[method]) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.stopwatch' );
}
};
})( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="example">
<div class="label">Count up from now</div>
<div id="demo1" class="demo">00:00</div>
</div>
<button class="add_time">add</button>
<button class="totall_time">totall time</button>

jQuery extended function preserve chaining based on condition

I'm trying to create a jquery build it function which will allow me to change maxHeight or retrieve maxHeight from an element or a set of elements.
setting a maxHeight by : $('.element-class').maxHeight(500); works great.
However when I dont pass a parameter in maxHeight() I'd like to return the element's height and not preserve jquery chainability:
Source:
(function($) {
// jQuery plugin definition
$.fn.maxHeight = function() {
var params = arguments;
var $this = this;
console.log(params);
this.each(function() {
var $t = $(this);
if (params.length > 0 ) {
if (params[0] == 'none'){
$t.get(0).style.maxHeight = 'none';
} else {
$t.get(0).style.maxHeight = params[0] + 'px';
}
return $t;
} else {
var h = (($t.get(0).style.maxHeight && $t.get(0).style.maxHeight != '') ? parseInt($t.get(0).style.maxHeight) : 0);
console.log(h);
return h;
}
});
return this;
};
})(jQuery);
I think you have to make a callback function, didn't have time to test it but try this:
(function($) {
// jQuery plugin definition
$.fn.maxHeight = function(a, callback) {
var $this = this;
this.each(function() {
var $t = $(this);
if (!a) {
$t.get(0).style.maxHeight = 'none';
} else {
$t.get(0).style.maxHeight = a + 'px';
}
callback($t);
} else {
var h = (($t.get(0).style.maxHeight && $t.get(0).style.maxHeight != '') ? parseInt($t.get(0).style.maxHeight) : 0);
callback(h);
}
});
};
})(jQuery);
and then do something like this:
$('.element-class').maxHeight(500 , function(result){
// use your result or not
// Want to chain
return result;
});

JavaScript Preventing User Text Selection

Something in this Curtains.js plug-in is preventing user text selection on my page. When I comment it out, I'm able to select text, when I put it back in, I'm not. Can someone identify it and tell me how to fix it? I'm at my wit's end.
<script>
/*
* Curtain.js - Create an unique page transitioning system
* ---
* Version: 2
* Copyright 2011, Victor Coulon (http://victorcoulon.fr)
* Released under the MIT Licence
*/
(function ( $, window, document, undefined ) {
var pluginName = 'curtain',
defaults = {
scrollSpeed: 400,
bodyHeight: 0,
linksArray: [],
mobile: false,
scrollButtons: {},
controls: null,
curtainLinks: '.curtain-links',
enableKeys: true,
easing: 'swing',
disabled: false,
nextSlide: function() {},
prevSlide: function() {}
};
// The actual plugin constructor
function Plugin( element, options ) {
var self = this;
// Public attributes
this.element = element;
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this._ignoreHashChange = false;
this.init();
}
Plugin.prototype = {
init: function () {
var self = this;
// Cache element
this.$element = $(this.element);
this.$li = $(this.element).find('>li');
this.$liLength = this.$li.length;
self.$windowHeight = $(window).height();
self.$elDatas = {};
self.$document = $(document);
self.$window = $(window);
self.webkit = (navigator.userAgent.indexOf('Chrome') > -1 || navigator.userAgent.indexOf("Safari") > -1);
$.Android = (navigator.userAgent.match(/Android/i));
$.iPhone = ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)));
$.iPad = ((navigator.userAgent.match(/iPad/i)));
$.iOs4 = (/OS [1-4]_[0-9_]+ like Mac OS X/i.test(navigator.userAgent));
if($.iPhone || $.iPad || $.Android || self.options.disabled){
this.options.mobile = true;
this.$li.css({position:'relative'});
this.$element.find('.fixed').css({position:'absolute'});
}
if(this.options.mobile){
this.scrollEl = this.$element;
} else if($.browser.mozilla || $.browser.msie) {
this.scrollEl = $('html');
} else {
this.scrollEl = $('body');
}
if(self.options.controls){
self.options.scrollButtons['up'] = $(self.options.controls).find('[href="#up"]');
self.options.scrollButtons['down'] = $(self.options.controls).find('[href="#down"]');
if(!$.iOs4 && ($.iPhone || $.iPad)){
self.$element.css({
position:'fixed',
top:0,
left:0,
right:0,
bottom:0,
'-webkit-overflow-scrolling':'touch',
overflow:'auto'
});
$(self.options.controls).css({position:'absolute'});
}
}
// When all image is loaded
var callbackImageLoaded = function(){
self.setDimensions();
self.$li.eq(0).addClass('current');
self.setCache();
if(!self.options.mobile){
if(self.$li.eq(1).length)
self.$li.eq(1).nextAll().addClass('hidden');
}
self.setEvents();
self.setLinks();
self.isHashIsOnList(location.hash.substring(1));
};
if(self.$element.find('img').length)
self.imageLoaded(callbackImageLoaded);
else
callbackImageLoaded();
},
// Events
scrollToPosition: function (direction){
var position = null,
self = this;
if(self.scrollEl.is(':animated')){
return false;
}
if(direction === 'up' || direction == 'down'){
// Keyboard event
var $next = (direction === 'up') ? self.$current.prev() : self.$current.next();
// Step in the current panel ?
if(self.$step){
if(!self.$current.find('.current-step').length){
self.$step.eq(0).addClass('current-step');
}
var $nextStep = (direction === 'up') ? self.$current.find('.current-step').prev('.step') : self.$current.find('.current-step').next('.step');
if($nextStep.length) {
position = (self.options.mobile) ? $nextStep.position().top + self.$elDatas[self.$current.index()]['data-position'] : $nextStep.position().top + self.$elDatas[self.$current.index()]['data-position'];
}
}
position = position || ((self.$elDatas[$next.index()] === undefined) ? null : self.$elDatas[$next.index()]['data-position']);
if(position !== null){
self.scrollEl.animate({
scrollTop: position
}, self.options.scrollSpeed, self.options.easing);
}
} else if(direction === 'top'){
self.scrollEl.animate({
scrollTop:0
}, self.options.scrollSpeed, self.options.easing);
} else if(direction === 'bottom'){
self.scrollEl.animate({
scrollTop:self.options.bodyHeight
}, self.options.scrollSpeed, self.options.easing);
} else {
var index = $("#"+direction).index(),
speed = Math.abs(self.currentIndex-index) * (this.options.scrollSpeed*4) / self.$liLength;
self.scrollEl.animate({
scrollTop:self.$elDatas[index]['data-position'] || null
}, (speed <= self.options.scrollSpeed) ? self.options.scrollSpeed : speed, this.options.easing);
}
},
scrollEvent: function() {
var self = this,
docTop = self.$document.scrollTop();
if(docTop < self.currentP && self.currentIndex > 0){
// Scroll to top
self._ignoreHashChange = true;
if(self.$current.prev().attr('id'))
self.setHash(self.$current.prev().attr('id'));
self.$current
.removeClass('current')
.css( (self.webkit) ? {'-webkit-transform': 'translateY(0px) translateZ(0)'} : {marginTop: 0} )
.nextAll().addClass('hidden').end()
.prev().addClass('current').removeClass('hidden');
self.setCache();
self.options.prevSlide();
} else if(docTop < (self.currentP + self.currentHeight)){
// Animate the current pannel during the scroll
if(self.webkit)
self.$current.css({'-webkit-transform': 'translateY('+(-(docTop-self.currentP))+'px) translateZ(0)' });
else
self.$current.css({marginTop: -(docTop-self.currentP) });
// If there is a fixed element in the current panel
if(self.$fixedLength){
var dataTop = parseInt(self.$fixed.attr('data-top'), 10);
if(docTop + self.$windowHeight >= self.currentP + self.currentHeight){
self.$fixed.css({
position: 'fixed'
});
} else {
self.$fixed.css({
position: 'absolute',
marginTop: Math.abs(docTop-self.currentP)
});
}
}
// If there is a step element in the current panel
if(self.$stepLength){
$.each(self.$step, function(i,el){
if(($(el).position().top+self.currentP) <= docTop+5 && $(el).position().top + self.currentP + $(el).height() >= docTop+5){
if(!$(el).hasClass('current-step')){
self.$step.removeClass('current-step');
$(el).addClass('current-step');
return false;
}
}
});
}
if(self.parallaxBg){
self.$current.css({
'background-position-y': docTop * self.parallaxBg
});
}
if(self.$fade.length){
self.$fade.css({
'opacity': 1-(docTop/ self.$fade.attr('data-fade'))
});
}
if(self.$slowScroll.length){
self.$slowScroll.css({
'margin-top' : (docTop / self.$slowScroll.attr('data-slow-scroll'))
});
}
} else {
// Scroll bottom
self._ignoreHashChange = true;
if(self.$current.next().attr('id'))
self.setHash(self.$current.next().attr('id'));
self.$current.removeClass('current')
.addClass('hidden')
.next('li').addClass('current').next('li').removeClass('hidden');
self.setCache();
self.options.nextSlide();
}
},
scrollMobileEvent: function() {
var self = this,
docTop = self.$element.scrollTop();
if(docTop+10 < self.currentP && self.currentIndex > 0){
// Scroll to top
self._ignoreHashChange = true;
if(self.$current.prev().attr('id'))
self.setHash(self.$current.prev().attr('id'));
self.$current.removeClass('current').prev().addClass('current');
self.setCache();
self.options.prevSlide();
} else if(docTop+10 < (self.currentP + self.currentHeight)){
// If there is a step element in the current panel
if(self.$stepLength){
$.each(self.$step, function(i,el){
if(($(el).position().top+self.currentP) <= docTop && (($(el).position().top+self.currentP) + $(el).outerHeight()) >= docTop){
if(!$(el).hasClass('current-step')){
self.$step.removeClass('current-step');
$(el).addClass('current-step');
}
}
});
}
} else {
// Scroll bottom
self._ignoreHashChange = true;
if(self.$current.next().attr('id'))
self.setHash(self.$current.next().attr('id'));
self.$current.removeClass('current').next().addClass('current');
self.setCache();
self.options.nextSlide();
}
},
// Setters
setDimensions: function(){
var self = this,
levelHeight = 0,
cover = false,
height = null;
self.$windowHeight = self.$window.height();
this.$li.each(function(index) {
var $self = $(this);
cover = $self.hasClass('cover');
if(cover){
$self.css({height: self.$windowHeight, zIndex: 999-index})
.attr('data-height',self.$windowHeight)
.attr('data-position',levelHeight);
self.$elDatas[$self.index()] = {
'data-height': parseInt(self.$windowHeight,10),
'data-position': parseInt(levelHeight, 10)
};
levelHeight += self.$windowHeight;
} else{
height = ($self.outerHeight() <= self.$windowHeight) ? self.$windowHeight : $self.outerHeight();
$self.css({minHeight: height, zIndex: 999-index})
.attr('data-height',height)
.attr('data-position',levelHeight);
self.$elDatas[$self.index()] = {
'data-height': parseInt(height, 10),
'data-position': parseInt(levelHeight, 10)
};
levelHeight += height;
}
if($self.find('.fixed').length){
var top = $self.find('.fixed').css('top');
$self.find('.fixed').attr('data-top', top);
}
});
if(!this.options.mobile)
this.setBodyHeight();
},
setEvents: function() {
var self = this;
$(window).on('resize', function(){
self.setDimensions();
});
if(self.options.mobile) {
self.$element.on('scroll', function(){
self.scrollMobileEvent();
});
} else {
self.$window.on('scroll', function(){
self.scrollEvent();
});
}
if(self.options.enableKeys) {
self.$document.on('keydown', function(e){
if(e.keyCode === 38 || e.keyCode === 37) {
self.scrollToPosition('up');
e.preventDefault();
return false;
}
if(e.keyCode === 40 || e.keyCode === 39){
self.scrollToPosition('down');
e.preventDefault();
return false;
}
// Home button
if(e.keyCode === 36){
self.scrollToPosition('top');
e.preventDefault();
return false;
}
// End button
if(e.keyCode === 35){
self.scrollToPosition('bottom');
e.preventDefault();
return false;
}
});
}
if(self.options.scrollButtons){
if(self.options.scrollButtons.up){
self.options.scrollButtons.up.on('click', function(e){
e.preventDefault();
self.scrollToPosition('up');
});
}
if(self.options.scrollButtons.down){
self.options.scrollButtons.down.on('click', function(e){
e.preventDefault();
self.scrollToPosition('down');
});
}
}
if(self.options.curtainLinks){
$(self.options.curtainLinks).on('click', function(e){
e.preventDefault();
var href = $(this).attr('href');
if(!self.isHashIsOnList(href.substring(1)) && position)
return false;
var position = self.$elDatas[$(href).index()]['data-position'] || null;
if(position){
self.scrollEl.animate({
scrollTop:position
}, self.options.scrollSpeed, self.options.easing);
}
return false;
});
}
self.$window.on("hashchange", function(event){
if(self._ignoreHashChange === false){
self.isHashIsOnList(location.hash.substring(1));
}
self._ignoreHashChange = false;
});
},
setBodyHeight: function(){
var h = 0;
for (var key in this.$elDatas) {
var obj = this.$elDatas[key];
h += obj['data-height'];
}
this.options.bodyHeight = h;
$('body').height(h);
},
setLinks: function(){
var self = this;
this.$li.each(function() {
var id = $(this).attr('id') || 0;
self.options.linksArray.push(id);
});
},
setHash: function(hash){
// "HARD FIX"
el = $('[href=#'+hash+']');
el.parent().siblings('li').removeClass('active');
el.parent().addClass('active');
if(history.pushState) {
history.pushState(null, null, '#'+hash);
}
else {
location.hash = hash;
}
},
setCache: function(){
var self = this;
self.$current = self.$element.find('.current');
self.$fixed = self.$current.find('.fixed');
self.$fixedLength = self.$fixed.length;
self.$step = self.$current.find('.step');
self.$stepLength = self.$step.length;
self.currentIndex = self.$current.index();
self.currentP = self.$elDatas[self.currentIndex]['data-position'];
self.currentHeight = self.$elDatas[self.currentIndex]['data-height'];
self.parallaxBg = self.$current.attr('data-parallax-background');
self.$fade = self.$current.find('[data-fade]');
self.$slowScroll = self.$current.find('[data-slow-scroll]');
},
// Utils
isHashIsOnList: function(hash){
var self = this;
$.each(self.options.linksArray, function(i,val){
if(val === hash){
self.scrollToPosition(hash);
return false;
}
});
},
readyElement: function(el,callback){
var interval = setInterval(function(){
if(el.length){
callback(el.length);
clearInterval(interval);
}
},60);
},
imageLoaded: function(callback){
var self = this,
elems = self.$element.find('img'),
len = elems.length,
blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
elems.bind('load.imgloaded',function(){
if (--len <= 0 && this.src !== blank || $(this).not(':visible')){
elems.unbind('load.imgloaded');
callback.call(elems,this);
}
}).each(function(){
if (this.complete || this.complete === undefined){
var src = this.src;
this.src = blank;
this.src = src;
}
});
}
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
}
});
};
})( jQuery, window, document );
</script>
First you would have to tell us how you are trying to select text (mouse, keyboard, touchscreen, etc.)
I bet my bitcoins on keyboard (but I don't have any).
Must be one of those
self.$document.on('keydown', function(e){
...
e.preventDefault();
which don't even document which keys these numbers stand for.
It's e.preventDefault() which prevents the default browser action from being performed.
If you're in Chrome devtools, you can use
monitorEvents(window, 'key')
to make sense of these.
Of course this bit may help a bit:
keyCode: 38
keyIdentifier: "Up"
So the code could be written readably by use of keyIdentifier instead of keyCode.
I don't know how compatible that would be across browsers.
Be warned that keydown keyCode values are different from keypress values (which actually insert real characters). keydown key codes will vary between keyboard layouts and locales.
See http://unixpapa.com/js/key.html for disgust and enlightenment, but mostly disgust.

Detect if clicking outside of element (Must support clicking in overlay elements)

Current best solution i have found:
ko.bindingHandlers.clickedIn = (function () {
function getBounds(element) {
var pos = element.offset();
return {
x: pos.left,
x2: pos.left + element.outerWidth(),
y: pos.top,
y2: pos.top + element.outerHeight()
};
}
function hitTest(o, l) {
function getOffset(o) {
for (var r = { l: o.offsetLeft, t: o.offsetTop, r: o.offsetWidth, b: o.offsetHeight };
o = o.offsetParent; r.l += o.offsetLeft, r.t += o.offsetTop);
return r.r += r.l, r.b += r.t, r;
}
for (var b, s, r = [], a = getOffset(o), j = isNaN(l.length), i = (j ? l = [l] : l).length; i;
b = getOffset(l[--i]), (a.l == b.l || (a.l > b.l ? a.l <= b.r : b.l <= a.r))
&& (a.t == b.t || (a.t > b.t ? a.t <= b.b : b.t <= a.b)) && (r[r.length] = l[i]));
return j ? !!r.length : r;
}
return {
init: function (element, valueAccessor) {
var target = valueAccessor();
$(document).click(function (e) {
if (element._clickedInElementShowing === false && target()) {
var $element = $(element);
var bounds = getBounds($element);
var possibleOverlays = $("[style*=z-index],[style*=absolute]").not(":hidden");
$.each(possibleOverlays, function () {
if (hitTest(element, this)) {
var b = getBounds($(this));
bounds.x = Math.min(bounds.x, b.x);
bounds.x2 = Math.max(bounds.x2, b.x2);
bounds.y = Math.min(bounds.y, b.y);
bounds.y2 = Math.max(bounds.y2, b.y2);
}
});
if (e.clientX < bounds.x || e.clientX > bounds.x2 ||
e.clientY < bounds.y || e.clientY > bounds.y2) {
target(false);
}
}
element._clickedInElementShowing = false;
});
$(element).click(function (e) {
e.stopPropagation();
});
},
update: function (element, valueAccessor) {
var showing = ko.utils.unwrapObservable(valueAccessor());
if (showing) {
element._clickedInElementShowing = true;
}
}
};
})();
It works by first query for all elements with either z-index or absolute position that are visible. It then hit tests those elemnts against the elemnet I want to hide if click outside. If its a hit I calculate a new bound retacle which takes into acount the overlay bounds.
Its not rock solid, but works. Please feel free to comment if you see problems with above approuch
Old question
I'm using Knockout but this applies to DOM/Javascript in general
Im trying to find a reliable way if detecting of you click outside of a element. My code looks like this
ko.bindingHandlers.clickedIn = {
init: function (element, valueAccessor) {
var target = valueAccessor();
var clickedIn = false;
ko.utils.registerEventHandler(document, "click", function (e) {
if (!clickedIn && element._clickedInElementShowing === false) {
target(e.target == element);
}
clickedIn = false;
element._clickedInElementShowing = false;
});
ko.utils.registerEventHandler(element, "click", function (e) {
clickedIn = true;
});
},
update: function (element, valueAccessor) {
var showing = ko.utils.unwrapObservable(valueAccessor());
if (showing) {
element._clickedInElementShowing = true;
}
}
};
It works by both listening to click on target element and document. If you click on document but not target element you click outside of it. This works, but, not for overlay items like datepickers etc. This is because these are not inside the target element but in the body. Can I fix this? Are there better way of determine if clicking outside of element?
edit: This kind of works, but only if the overlay is smaller than the element i want to monitor
ko.bindingHandlers.clickedIn = {
init: function (element, valueAccessor) {
var target = valueAccessor();
$(document).click(function (e) {
if (element._clickedInElementShowing === false) {
var $element = $(element);
var pos = $element.offset();
if (e.clientX < pos.left || e.clientX > (pos.left + $element.width()) ||
e.clientY < pos.top || e.clientY > (pos.top + $element.height())) {
target(false);
}
}
element._clickedInElementShowing = false;
});
$(element).click(function (e) {
e.stopPropagation();
});
},
update: function (element, valueAccessor) {
var showing = ko.utils.unwrapObservable(valueAccessor());
if (showing) {
element._clickedInElementShowing = true;
}
}
};
I would like a more rock solid approuch
This is how I usually solve it:
http://jsfiddle.net/jonigiuro/KLxnV/
$('.container').on('click', function(e) {
alert('hide the child');
});
$('.child').on('click', function(e) {
alert('do nothing');
e.stopPropagation(); //THIS IS THE IMPORTANT PART
});
I don't know how your overlay items are generated, but you could always check if the click target is a child of the element you want to constrain your clicks to.

Categories

Resources