Skip to content

Instantly share code, notes, and snippets.

@kubosho
Created October 13, 2012 12:57
Show Gist options
  • Save kubosho/3884566 to your computer and use it in GitHub Desktop.
Save kubosho/3884566 to your computer and use it in GitHub Desktop.
一回しか実行されない関数のテスト
以下のURLで紹介されている関数を自作ライブラリで使ってみた。
最初の一回だけ実行される関数を生成する関数 #JavaScript - Qiita http://qiita.com/items/631bb3ef2a34064b0d86
* {
margin: 0;
padding: 0;
}
.testElement {
width: 200px;
height: 150px;
margin-bottom: 10px;
background-color: #CCC;
&:last-child {
margin-bottom: 0;
}
}
#target {
border: 10px solid #CCC;
background-color: #EEE;
}
<div class="testElement"></div>
<div class="testElement"></div>
<div class="testElement"></div>
<div class="testElement"></div>
<div class="testElement"></div>
<div id="target" class="testElement"></div>
<div class="testElement"></div>
<div class="testElement"></div>
(function (window, document, $, undefined) {
'use strict';
/**
* @constructor
* @param {Selector} selector
* @param {Number} pixel
* @param {Object} func
* @example
* var scrollVisible = new ScrollVisible('.selector', 50, func, callback);
*
* document.addEventListener('scroll', function () {
* scrollVisible.start();
* }, false);
*/
function ScrollVisible(selector, pixel, func, callback) {
this.init.apply(this, arguments);
}
ScrollVisible.prototype = {
init: function (selector, pixel, func, callback) {
this.selector = selector;
this.px = pixel;
this._func = func;
this._callback = callback || function () {};
this._win = {
w: $(window).width(),
h: $(window).height()
};
},
start: function () {
var position = {
elmX: 0,
elmY: 0,
scrollX: 0,
scrollY: 0
},
mathState = 0;
position.elmX = $(this.selector).offset().left;
position.elmY = $(this.selector).offset().top;
position.scrollX = $(document).scrollLeft();
position.scrollY = $(document).scrollTop();
mathState = (this._win.h + position.scrollY) - (position.elmY + this.px);
console.log(mathState);
console.log(this.px);
if (mathState <= this.px) {
return this._func();
}
},
stop: function() {
return this._callback();
}
};
window.ScrollVisible = ScrollVisible;
}(window, document, jQuery));
$(function () {
var scrollVisible = new ScrollVisible('#target', 50, function () {
console.log('Hello world!');
});
document.addEventListener('scroll', function () {
scrollVisible.start();
}, false);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment