I'm currently developing a Drag n' Drop plugin. I have just finished a feature so people could drop the draggable item on a target. Now it works perfect on the jsfiddle:
http://jsfiddle.net/XvZLn/18/
But once I implement that code into my plugin the following wont work:
var target = {
on: function() {
return $('.drag:first').each(function() {
$(this).addClass('i');
});
},
off: function() {
$('.drag:first').removeClass('i');
}
};
Which in my plugin it looks like this:
var targ = {
on: o.target.onTarget,
off: o.target.offTarget
};
Both of the codes have there purposes. The the on part is the function that is suppose to be launched when you enter all the way in the target. The off part is the function that gets launched when leaving the target.
onTarget and offTarget are all options in the defaults.
The reason we this var is because we needed a way to use function(){}.
The only way I thought I could do this is in an var.
Now Im trying to launch targ.on() inside the if that checks if the element is all the way inside the target. This is not working. I know the targ.on() is not working because I added an alert in the if and and I got the alert once the element got in the target.
This the the full code I use in my plugin:
var locker = o.target.lock;
var lock = false;
var targ = {
on: o.target.onTarget,
off: o.target.offTarget
};
$(oj).bind('drag', function (event) {
var $t = $(this);
var $con = $(o.target.init);
if (lock === false) {
$(this).css({
top: event.offsetY,
left: event.offsetX
});
}
}).bind('mouseup', function () {
var $t = $(this);
var $con = $(o.target.init);
var sen = 100;
var otop = $t.offset().top;
var oleft = $t.offset().left;
var conw = $con.width();
var conh = $con.height();
var cono = $con.offset().top;
var conl = $con.offset().left;
var oo = $t.height();
sen = sen * 2;
var other = oleft <= conw - (sen / 1.25) && oleft > conl && oleft < conw + conl - (sen / 4);
if (locker === false) {
if (otop < conw - (sen / 4) && otop > cono && otop < ((conh + cono) - oo) && other) {
targ.on();
lock = false;
} else {
targ.off();
lock = false;
}
} else {
if (otop < conw - (sen / 4) && otop > cono && otop < ((conh + cono) - oo) && other) {
targ.on();
$(this).css('cursor', 'default');
lock = true;
}
}
});
Full Plugin Code:
$.setCookie = function(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
};
$.getCookie = function(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
};
$.fn.jDrag = function(options) {
var getVersion = {
version: '1.0.0',
version2: '1.0.0',
version3: '1.0.1'
};
var defaults = {
revert: false,
revertDuration: 500,
ghostDrop: false,
ghostRevert: false,
ghostOpacity: '0.50',
instantGhost: false,
activeClass: false,
handle: false,
grid: false,
cookies: false,
cookieExdate: 365,
radialDrag: false,
radius: 100,
circularOutline: false,
strictMovement: false,
distance: 0,
not: false,
containment: false,
target: {
init: false,
lock: false,
onTarget: function() {},
offTarget: function() {}
},
onPickUp: function() {},
onDrop: function() {}
};
var o = $.extend(defaults, options);
$('body').append('<span class="version_usage_neededToReCievever_srion-now" style="display:none;">' + getVersion.version2 + '</span>');
return this.each(function() {
//Some Variables
var oj = this,
position = $(oj).position(),
revertLeft = position.left,
revertTop = position.top,
yea = 'body',
onceInawhile = '<b class="getDistanceAsofPosition" style="display:none;">' + o.distance + '</b>';
if (o.not === oj) {
o.not = false;
}
o.distance = squared(o.distance);
//alert(o.distance);
var m;
var t;
$(oj).bind('mousedown', function() {
m = event.pageX;
t = event.pageY;
//$('#hi').text(m+' '+t);
});
var firstofdrag = '<b class="getnotNoCondition" style="display:none;">"' + o.not + '"</b>';
if (o.ghostDrop === true) {
var random = Math.floor(Math.random() * 9999999);
if (o.ghostRevert === false) {
o.revert = false;
}
if (o.ghostRevert === true) {
o.revert = true;
}
$(document).ready(function() {
$(oj).clone().attr('id', '').addClass('ghosts').addClass('ghost_starter' + random).css({
position: 'absolute',
top: revertTop,
left: revertLeft,
opacity: o.ghostOpacity
}).appendTo('body');
$('.ghost_starter' + random).mousedown(function() {
if (o.activeClass !== false) {
$(this).addClass(o.activeClass);
}
}).bind('mousedown', o.onPickUp).bind('drag', function(event) {
if (o.grid !== false) {
if (o.not !== false && $(event.target).is(o.not)) {
return false;
} else {
if (o.strictMovement !== false || o.strictMovement === 'horizontal' || o.strictMovement === 'x') {
$(this).css('left', Math.round(event.offsetX / defaults.grid[0]) * defaults.grid[0]);
}
else if (o.strictMovement !== false || o.strictMovement === 'vertical' || o.strictMovement === 'y') {
$(this).css('top', Math.round(event.offsetX / defaults.grid[1]) * defaults.grid[1]);
} else {
$(this).css({
top: Math.round(event.offsetY / defaults.grid[1]) * defaults.grid[1],
left: Math.round(event.offsetX / defaults.grid[0]) * defaults.grid[0]
});
}
}
}
else if (o.containment !== false) {
var $div = (o.containment === 'parent') ? $(oj).parent() : ((o.containment === 'parent parent') ? $(oj).parent().parent() : ((o.containment === 'document') ? $(document) : $(o.containment)));
var j, b, r;
$('.ghost_starter' + random).bind("dragstart", function(event) {
j = $div.offset();
b = j.top + $div.outerHeight() - $(this).outerHeight();
r = j.left + $div.outerWidth() - $(this).outerWidth();
}).bind('drag', function(event) {
$(this).css({
top: Math.min(b, Math.max(j.top, event.offsetY)),
left: Math.min(r, Math.max(j.left, event.offsetX))
});
});
}
else {
if (o.not !== false && $(event.target).is(o.not)) {
return false;
} else {
if (o.strictMovement !== false || o.strictMovement === 'horizontal' || o.strictMovement === 'x') {
$(this).css('left', event.offsetX);
}
else if (o.strictMovement !== false || o.strictMovement === 'vertical' || o.strictMovement === 'y') {
$(this).css('top', event.offsetY);
} else {
$(this).css({
top: event.offsetY,
left: event.offsetX
});
}
}
}
}).bind('mouseup', o.onDrop);
$(window).mouseup(function() {
if (o.activeClass !== false) {
$('.ghost_starter' + random).removeClass(o.activeClass);
}
var gpos = $('.ghost_starter' + random).position(),
lft = gpos.left,
tp = gpos.top;
$(oj).animate({
top: tp,
left: lft
}, 300);
if (o.cookies !== false) {
var cookies = $('.ghost_starter' + random).position();
if (o.cookieExdate === 'browserClose') {
$.setCookie('jDrag-Position-Top-Ghost' + $('.ghost_starter' + random).index(), cookies.top);
$.setCookie('jDrag-Position-Left-Ghost' + $('.ghost_starter' + random).index(), cookies.left);
} else {
$.setCookie('jDrag-Position-Top-Ghost' + $('.ghost_starter' + random).index(), cookies.top, o.cookieExdate);
$.setCookie('jDrag-Position-Left-Ghost' + $('.ghost_starter' + random).index(), cookies.left, o.cookieExdate);
}
}
});
});
}
if (o.distance !== false) {
$(yea).append(onceInawhile);
}
$('body').append('<span class="version_usage_neededToReCievever_srion-future" style="display:none;">' + getVersion.version3 + '</span>');
if (o.radialDrag === true) {
$(document).ready(function() {
if (o.circularOutline === true) {
$('head').append('<span class="hi"><div class="circularStyle"></div></span>');
$('.circularStyle').html('<style type="text/css">.pointlikeamaster{' + 'position: absolute;height: 4px;width: 4px;' + 'margin: -2px 0 0 -2px;background: #A00;' + '}</style>');
}
});
$(oj).bind('dragstart', function(event) {
var data = $(this).data('dragcircle');
if (data) {
data.$circle.show();
}
else {
data = {
radius: o.radius,
$circle: $([]),
halfHeight: $(this).outerHeight() / 2,
halfWidth: $(this).outerWidth() / 2
};
data.centerX = event.offsetX + data.radius + data.halfWidth;
data.centerY = event.offsetY + data.halfHeight;
// create divs to highlight the path...
$.each(new Array(72), function(i, a) {
angle = Math.PI * ((i - 36) / 36);
data.$circle = data.$circle.add(
$('<div class="pointlikeamaster" />').css({
top: data.centerY + Math.cos(angle) * data.radius,
left: data.centerX + Math.sin(angle) * data.radius
}));
});
$(this).after(data.$circle).data('dragcircle', data);
}
}).bind('drag', function(event) {
var data = $(this).data('dragcircle'),
angle = Math.atan2(event.pageX - data.centerX, event.pageY - data.centerY);
$(this).css({
top: data.centerY + Math.cos(angle) * data.radius - data.halfHeight,
left: data.centerX + Math.sin(angle) * data.radius - data.halfWidth
});
}).bind('dragend', function() {
$(this).data('dragcircle').$circle.hide();
});
} else {
$(oj).mousedown(function() {
if (o.activeClass !== false) {
$(this).addClass(o.activeClass);
}
}).bind('mousedown', o.onPickUp);
if (o.handle !== false) {
$(o.handle).mouseover(function() {
$(this).css({
cursor: 'crosshair'
});
});
$(oj).bind('dragstart', function(event) {
if (o.not !== false && $(event.target).is(o.not)) {
return false;
} else {
return $(event.target).is(o.handle);
}
}).bind('drag', function(event) {
if (o.grid !== false) {
if (o.not !== false && $(event.target).is(o.not)) {
return false;
} else {
if (o.strictMovement !== false || o.strictMovement === 'horizontal' || o.strictMovement === 'x') {
$(this).css('left', Math.round(event.offsetX / defaults.grid[0]) * defaults.grid[0]);
}
else if (o.strictMovement !== false || o.strictMovement === 'vertical' || o.strictMovement === 'y') {
$(this).css('top', Math.round(event.offsetX / defaults.grid[1]) * defaults.grid[1]);
} else {
$(this).css({
top: Math.round(event.offsetY / defaults.grid[1]) * defaults.grid[1],
left: Math.round(event.offsetX / defaults.grid[0]) * defaults.grid[0]
});
}
}
}
else if (o.containment !== false) {
var $div = (o.containment === 'parent') ? $(oj).parent() : ((o.containment === 'parent parent') ? $(oj).parent().parent() : ((o.containment === 'document') ? $(document) : $(o.containment)));
var j, b, r;
$(oj).bind("dragstart", function(event) {
j = $div.offset();
b = j.top + $div.outerHeight() - $(this).outerHeight();
r = j.left + $div.outerWidth() - $(this).outerWidth();
}).bind('drag', function(event) {
$(this).css({
top: Math.min(b, Math.max(j.top, event.offsetY)),
left: Math.min(r, Math.max(j.left, event.offsetX))
});
});
}
else {
if (o.not !== false && $(event.target).is(o.not)) {
return false;
} else {
if (o.strictMovement !== false || o.strictMovement === 'horizontal' || o.strictMovement === 'x') {
$(this).css('left', event.offsetX);
}
else if (o.strictMovement !== false || o.strictMovement === 'vertical' || o.strictMovement === 'y') {
$(this).css('top', event.offsetY);
} else {
$(this).css({
top: event.offsetY,
left: event.offsetX
});
}
}
}
});
} else {
$(oj).bind('drag', function(event) {
if (o.grid !== false) {
if (o.not !== false && $(event.target).is(o.not)) {
return false;
} else {
if (o.strictMovement !== false || o.strictMovement === 'horizontal') {
$(this).css('left', Math.round(event.offsetX / defaults.grid[0]) * defaults.grid[0]);
}
else if (o.strictMovement !== false || o.strictMovement === 'vertical') {
$(this).css('top', Math.round(event.offsetX / defaults.grid[1]) * defaults.grid[1]);
} else {
$(this).css({
top: Math.round(event.offsetY / defaults.grid[1]) * defaults.grid[1],
left: Math.round(event.offsetX / defaults.grid[0]) * defaults.grid[0]
});
}
}
}
else if (o.containment !== false) {
var $div = (o.containment === 'parent') ? $(oj).parent() : ((o.containment === 'parent parent') ? $(oj).parent().parent() : ((o.containment === 'document') ? $(document) : $(o.containment)));
var j, b, r;
$(oj).bind("dragstart", function(event) {
j = $div.offset();
b = j.top + $div.outerHeight() - $(this).outerHeight();
r = j.left + $div.outerWidth() - $(this).outerWidth();
}).bind('drag', function(event) {
$(this).css({
top: Math.min(b, Math.max(j.top, event.offsetY)),
left: Math.min(r, Math.max(j.left, event.offsetX))
});
});
}
else if (o.target.init !== false) {
/*
Use this to adjust the target settings
$('b').html(otop+' < '+(conw - (sen/4))+' && '+otop+' > '+cono+' && '+otop+' <= '+((conh + cono)-oo)+' && '+oleft+' < '+(conw-(sen/1.25))+' && '+oleft+' > '+conl+' && '+oleft+' < '+(conw + conl-(sen/4)));
var other = oleft <= conw - (sen/1.25) && oleft > conl && oleft < conw + conl - (sen / 4);
*/
var locker = o.target.lock;
var lock = false;
var targ = {
on: o.target.onTarget,
off: o.target.offTarget
};
$(oj).bind('drag', function(event) {
var $t = $(this);
var $con = $(o.target.init);
if (lock === false) {
$(this).css({
top: event.offsetY,
left: event.offsetX
});
}
}).bind('mouseup', function() {
var $t = $(this);
var $con = $(o.target.init);
var sen = 100;
var otop = $t.offset().top;
var oleft = $t.offset().left;
var conw = $con.width();
var conh = $con.height();
var cono = $con.offset().top;
var conl = $con.offset().left;
var oo = $t.height();
sen = sen * 2;
var other = oleft <= conw - (sen / 1.25) && oleft > conl && oleft < conw + conl - (sen / 4);
if (locker === false) {
if (otop < conw - (sen / 4) && otop > cono && otop < ((conh + cono) - oo) && other) {
targ.on();
lock = false;
} else {
targ.off();
lock = false;
}
} else {
if (otop < conw - (sen / 4) && otop > cono && otop < ((conh + cono) - oo) && other) {
targ.on();
$(this).css('cursor', 'default');
lock = true;
}
}
});
} else {
if (o.not !== false && $(event.target).is(o.not)) {
return false;
} else {
if (o.strictMovement !== false || o.strictMovement === 'horizontal') {
$(this).css('left', event.offsetX);
}
else if (o.strictMovement !== false || o.strictMovement === 'vertical') {
$(this).css('top', event.offsetY);
} else {
$(this).css({
top: event.offsetY,
left: event.offsetX
});
}
}
}
});
}
$(oj).bind('mouseup', o.onDrop);
$(window).mouseup(function() {
if (o.activeClass !== false) {
$(oj).removeClass(o.activeClass);
}
if (o.revert === true) {
$(oj).animate({
top: revertTop,
left: revertLeft
}, o.revertDuration);
}
if (o.cookies !== false) {
var cookies = $(oj).position();
if (o.cookieExdate === 'browserClose') {
$.setCookie('jDrag-Position-Top' + $(oj).index(), cookies.top);
$.setCookie('jDrag-Position-Left' + $(oj).index(), cookies.left);
} else {
$.setCookie('jDrag-Position-Top' + $(oj).index(), cookies.top, o.cookieExdate);
$.setCookie('jDrag-Position-Left' + $(oj).index(), cookies.left, o.cookieExdate);
}
}
});
}
if (o.not !== false) {
$(yea).append(firstofdrag);
}
$('body').append('<span class="version_usage_neededToReCievever_srion-past" style="display:none;">' + getVersion.version + '</span>');
if (o.instantGhost === true) {
window.setInterval(function() {
var gpos = $('.ghost_starter' + random).position(),
lft = gpos.left,
tp = gpos.top;
$(oj).stop(true, false).animate({
top: tp,
left: lft
}, 200);
}, 200);
}
//End normal Dragging
//End Tags
if (o.cookies === false) {
$(function() {
var oj = this;
if (o.ghostDrop === true) {
var savedLeftPosition = $.getCookie('jDrag-Position-Left-Ghost' + $(oj).index()),
savedTopPosition = $.getCookie('jDrag-Position-Top-Ghost' + $(oj).index());
$(oj).css({
left: savedLeftPosition + 'px',
top: savedTopPosition + 'px'
});
$('.ghost_starter' + random).css({
left: savedLeftPosition + 'px',
top: savedTopPosition + 'px'
});
}
});
} else {
var savedLeftPosition1 = $.getCookie('jDrag-Position-Left' + $(oj).index()),
savedTopPosition1 = $.getCookie('jDrag-Position-Top' + $(oj).index());
$(oj).css({
left: savedLeftPosition1 + 'px',
top: savedTopPosition1 + 'px'
});
}
});
};
I had to leave out the top part of the plugin because it told me there is a 30000 character limit.
Example: http://jsfiddle.net/ZDUZL/84/
Im not sure what the problem is, and im not sure if this is too much information or not. Thanks for any help.
This works in your first jsFiddle because you're relying on the offset directly from the drag event object:
$('.drag').bind('drag', function(event) {
var $t = $(this);
var $con = $('#container');
if (lock === false) {
$(this).css({
top: event.offsetY, // coordinates directly from event object
left: event.offsetX
});
}
})...
In the full plugin code, you get an offset in your dragstart event callback and then try to reference it from your drag event callback. The problem is that this dragstart event is not being triggered (or not at the proper time or on the proper element, anyway). When the drag callback looks for the values, they're undefined and your script is halted on the error. See here for reference:
var $div = (o.containment === 'parent') ? $(oj).parent() : ((o.containment === 'parent parent') ? $(oj).parent().parent() : ((o.containment === 'document') ? $(document) : $(o.containment)));
var j, b, r;
$('.ghost_starter' + random).bind("dragstart", function(event) { // this event isn't being triggered (or at least not at the right time or on the right element)...
j = $div.offset();
b = j.top + $div.outerHeight() - $(this).outerHeight();
r = j.left + $div.outerWidth() - $(this).outerWidth();
}).bind('drag', function(event) {
$(this).css({
top: Math.min(b, Math.max(j.top, event.offsetY)), // ...so b, j, and r aren't defined here
left: Math.min(r, Math.max(j.left, event.offsetX))
});
});
Fix that dragstart trigger or get your offset otherwise and you'll be set.
Related
I was trying to do a full page scroll while using anchor links throughout the page but sometimes it won't scroll up anymore or the links stop working or go to the wrong places. It gets pushed down leaving strange white space after I scroll around an press on the links.
Link to code:
https://codepen.io/serelath/pen/NEzyxL
I appreciate it if anyone can look into this for me.
(function() {
"use strict";
/*[pan and well CSS scrolls]*/
var pnls = document.querySelectorAll('.panel').length,
scdir, hold = false;
function _scrollY(obj) {
var slength, plength, pan, step = 100,
vh = window.innerHeight / 100,
vmin = Math.min(window.innerHeight, window.innerWidth) / 100;
if ((this !== undefined && this.id === 'well') || (obj !== undefined && obj.id === 'well')) {
pan = this || obj;
plength = parseInt(pan.offsetHeight / vh);
}
if (pan === undefined) {
return;
}
plength = plength || parseInt(pan.offsetHeight / vmin);
slength = parseInt(pan.style.transform.replace('translateY(', ''));
if (scdir === 'up' && Math.abs(slength) < (plength - plength / pnls)) {
slength = slength - step;
} else if (scdir === 'down' && slength < 0) {
slength = slength + step;
} else if (scdir === 'top') {
slength = 0;
}
if (hold === false) {
hold = true;
pan.style.transform = 'translateY(' + slength + 'vh)';
setTimeout(function() {
hold = false;
}, 500);
}
console.log(scdir + ':' + slength + ':' + plength + ':' + (plength - plength / pnls));
}
/*[swipe detection on touchscreen devices]*/
function _swipe(obj) {
var swdir,
sX,
sY,
dX,
dY,
threshold = 100,
/*[min distance traveled to be considered swipe]*/
slack = 50,
/*[max distance allowed at the same time in perpendicular direction]*/
alT = 300,
/*[max time allowed to travel that distance]*/
elT, /*[elapsed time]*/
stT; /*[start time]*/
obj.addEventListener('touchstart', function(e) {
var tchs = e.changedTouches[0];
swdir = 'none';
sX = tchs.pageX;
sY = tchs.pageY;
stT = new Date().getTime();
//e.preventDefault();
}, false);
obj.addEventListener('touchmove', function(e) {
e.preventDefault(); /*[prevent scrolling when inside DIV]*/
}, false);
obj.addEventListener('touchend', function(e) {
var tchs = e.changedTouches[0];
dX = tchs.pageX - sX;
dY = tchs.pageY - sY;
elT = new Date().getTime() - stT;
if (elT <= alT) {
if (Math.abs(dX) >= threshold && Math.abs(dY) <= slack) {
swdir = (dX < 0) ? 'left' : 'right';
} else if (Math.abs(dY) >= threshold && Math.abs(dX) <= slack) {
swdir = (dY < 0) ? 'up' : 'down';
}
if (obj.id === 'well') {
if (swdir === 'up') {
scdir = swdir;
_scrollY(obj);
} else if (swdir === 'down' && obj.style.transform !== 'translateY(0)') {
scdir = swdir;
_scrollY(obj);
}
e.stopPropagation();
}
}
}, false);
}
/*[assignments]*/
var well = document.getElementById('well');
well.style.transform = 'translateY(0)';
well.addEventListener('wheel', function(e) {
if (e.deltaY < 0) {
scdir = 'down';
}
if (e.deltaY > 0) {
scdir = 'up';
}
e.stopPropagation();
});
well.addEventListener('wheel', _scrollY);
_swipe(well);
var tops = document.querySelectorAll('.top');
for (var i = 0; i < tops.length; i++) {
tops[i].addEventListener('click', function() {
scdir = 'top';
_scrollY(well);
});
}
})();
On my HTML page, I need to have a line with text that rolls "infinitely" on the page, e.g.
"Hello World ... Hello World ... Hello World ... Hello World ..."
Sort of like a ticker tape, but with the same text's beginning rolling into its end w/o a gap.
I've tried using animation: marquee CSS style, I can get the text roll, then jump back, then roll again, but that's not what I need.
Is this possible with CSS? JS would be OK, if there is a working solution.
Try here "text rolling" working with text & images and mouse effects(js+css)
http://www.dynamicdrive.com/dynamicindex2/crawler/index.htm
Are you open to using a lib that does this?
This one here: http://www.cssscript.com/marquee-like-horizontal-scroller-with-pure-javascript-marquee-js/ does a good job.
$(document).ready(function() {
new Marquee('example', {
// once or continuous
continuous: true,
// 'rtl' or 'ltr'
direction: 'rtl',
// pause between loops
delayAfter: 1000,
// when to start
delayBefore: 0,
// scroll speed
speed: 0.5,
// loops
loops: -1
});
});
////////////////////////////// LIBRARY BELOW ///////
// See: http://www.cssscript.com/marquee-like-horizontal-scroller-with-pure-javascript-marquee-js/
/*
Vanilla Javascript Marquee
Version: 0.1.0
Author: Robert Bossaert <https://github.com/robertbossaert>
Example call:
new Marquee('element');
new Marquee('element', {
direction: 'rtl',
});
*/
var Marquee = function(element, defaults) {
"use strict";
var elem = document.getElementById(element),
options = (defaults === undefined) ? {} : defaults,
continuous = options.continuous || true, // once or continuous
delayAfter = options.delayAfter || 1000, // pause between loops
delayBefore = options.delayBefore || 0, // when to start
direction = options.direction || 'ltr', // ltr or rtl
loops = options.loops || -1,
speed = options.speed || 0.5,
timer = null,
milestone = 0,
marqueeElem = null,
elemWidth = null,
self = this,
ltrCond = 0,
loopCnt = 0,
start = 0,
process = null,
constructor = function(elem) {
// Build html
var elemHTML = elem.innerHTML,
elemNode = elem.childNodes[1] || elem;
elemWidth = elemNode.offsetWidth;
marqueeElem = '<div>' + elemHTML + '</div>';
elem.innerHTML = marqueeElem;
marqueeElem = elem.getElementsByTagName('div')[0];
elem.style.overflow = 'hidden';
marqueeElem.style.whiteSpace = 'nowrap';
marqueeElem.style.position = 'relative';
if (continuous === true) {
marqueeElem.innerHTML += elemHTML;
marqueeElem.style.width = '200%';
if (direction === 'ltr') {
start = -elemWidth;
}
} else {
ltrCond = elem.offsetWidth;
if (direction === 'rtl') {
milestone = ltrCond;
}
}
if (direction === 'ltr') {
milestone = -elemWidth;
} else if (direction === 'rtl') {
speed = -speed;
}
self.start();
return marqueeElem;
}
this.start = function() {
process = window.setInterval(function() {
self.play();
});
};
this.play = function() {
// beginning
marqueeElem.style.left = start + 'px';
start = start + speed;
if (start > ltrCond || start < -elemWidth) {
start = milestone;
loopCnt++;
if (loops !== -1 && loopCnt >= loops) {
marqueeElem.style.left = 0;
}
}
}
this.end = function() {
window.clearInterval(process);
}
// Init plugin
marqueeElem = constructor(elem);
}
body {
background: #edf3f9;
color: #3f4f5f;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.container {
margin: 0 auto;
width: 800px;
}
header {
border-bottom: 2px solid #3f4f5f;
padding: 6.25em 0 3.95em;
text-align: center;
width: 100%;
}
header h1 {
margin: 0 0 10px;
}
.example {
padding: 3em 0;
}
h2 {
text-align: center;
}
pre {
background: #f5f2f0;
color: #000;
font-family: Consolas, Monaco, 'Andale Mono', monospace;
line-height: 26px;
padding: 1em;
text-shadow: 0 1px white;
white-space: pre-wrap;
}
pre span.string {
color: #690;
}
pre span.number {
color: #905;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example">
The quick brown fox ran over to the bar to drink some water. He walked up to the bar tender and said: blah blah blah.
</div>
Here is a demo based upon the lib that Dreamer posted.
I didn't like how it set inline styles on the element or how it used cookies to store past settings so I removed that in the crawler.js code.
This is a pretty old library (ie5 is mentioned (!)) but it seems to do the trick.
$(function() {
marqueeInit({
uniqueid: 'mycrawler',
style: {
},
inc: 5, //speed - pixel increment for each iteration of this marquee's movement
mouse: 'cursor driven', //mouseover behavior ('pause' 'cursor driven' or false)
moveatleast: 2,
neutral: 150,
persist: true,
savedirection: true
});
});
//////////////// CRAWLER.JS FOLLOWS ///////////
/* Text and/or Image Crawler Script v1.53 (c)2009-2012 John Davenport Scheuer
as first seen in http://www.dynamicdrive.com/forums/
username: jscheuer1 - This Notice Must Remain for Legal Use
updated: 4/2011 for random order option, more (see below)
*/
/* Update 4/2011 to v1.5 - Adds optional random property. Set it to true to use.
Fixes browser crash from empty crawlers, ad and image blocking software/routines.
Fixes behavior in some IE of breaking script if an image is missing.
Adds alt attributes to images without them to aid in diagnosis of missing/corrupt
images. This may be disabled with the new optional noAddedAlt property set to true.
Internal workings enhanced for greater speed of execution, less memory usage.
*/
/* Update 11/2011 - Detect and randomize td elements within a single table with a single tr */
// updated 7/2012 to 1.51 for optional integration with 3rd party initializing scripts -
// ref: http://www.dynamicdrive.com/forums/showthread.php?p=278161#post278161
// updated 8/2012 to 1.52 for greater compatibility with IE in Quirks Mode
/* Update 10/2012 to v1.53 - Adds optional persist property to have the crawler remember its
position and direction page to page and on page reload. To enable it in the marqueeInit set
persist: true,
*/
///////////////// No Need to Edit - Configuration is Done in the On Page marqueeInit call(s) /////////////////
function marqueeInit(config) {
if (!document.createElement) return;
marqueeInit.ar.push(config);
marqueeInit.run(config.uniqueid);
}
(function() {
if (!document.createElement) return;
if (typeof opera === 'undefined') {
window.opera = false;
}
marqueeInit.ar = [];
document.write('<style type="text/css">.marquee{white-space:nowrap;overflow:hidden;visibility:hidden;}' +
'#marq_kill_marg_bord{border:none!important;margin:0!important;}<\/style>');
var c = 0,
tTRE = [/^\s*$/, /^\s*/, /\s*$/, /[^\/]+$/],
req1 = {
'position': 'relative',
'overflow': 'hidden'
},
defaultconfig = {
style: { //default style object for marquee containers without configured style
'margin': '0 auto'
},
direction: 'left',
inc: 2, //default speed - pixel increment for each iteration of a marquee's movement
mouse: 'pause' //default mouseover behavior ('pause' 'cursor driven' or false)
},
dash, ie = false,
oldie = 0,
ie5 = false,
iever = 0;
/*#cc_on #*/
/*#if(#_jscript_version >= 5)
ie = true;
try{document.documentMode = 2000}catch(e){};
iever = Math.min(document.documentMode, navigator.appVersion.replace(/^.*MSIE (\d+\.\d+).*$/, '$1'));
if(iever < 6)
oldie = 1;
if(iever < 5.5){
Array.prototype.push = function(el){this[this.length] = el;};
ie5 = true;
dash = /(-(.))/;
String.prototype.encamel = function(s, m){
s = this;
while((m = dash.exec(s)))
s = s.replace(m[1], m[2].toUpperCase());
return s;
};
}
#end #*/
if (!ie5) {
dash = /-(.)/g;
function toHump(a, b) {
return b.toUpperCase();
};
String.prototype.encamel = function() {
return this.replace(dash, toHump);
};
}
if (ie && iever < 8) {
marqueeInit.table = [];
window.attachEvent('onload', function() {
marqueeInit.OK = true;
var i = -1,
limit = marqueeInit.table.length;
while (++i < limit)
marqueeInit.run(marqueeInit.table[i]);
});
}
function intable(el) {
while ((el = el.parentNode))
if (el.tagName && el.tagName.toLowerCase() === 'table')
return true;
return false;
};
marqueeInit.run = function(id) {
if (ie && !marqueeInit.OK && iever < 8 && intable(document.getElementById(id))) {
marqueeInit.table.push(id);
return;
}
if (!document.getElementById(id))
setTimeout(function() {
marqueeInit.run(id);
}, 300);
else
new Marq(c++, document.getElementById(id));
}
function trimTags(tag) {
var r = [],
i = 0,
e;
while ((e = tag.firstChild) && e.nodeType === 3 && tTRE[0].test(e.nodeValue))
tag.removeChild(e);
while ((e = tag.lastChild) && e.nodeType === 3 && tTRE[0].test(e.nodeValue))
tag.removeChild(e);
if ((e = tag.firstChild) && e.nodeType === 3)
e.nodeValue = e.nodeValue.replace(tTRE[1], '');
if ((e = tag.lastChild) && e.nodeType === 3)
e.nodeValue = e.nodeValue.replace(tTRE[2], '');
while ((e = tag.firstChild))
r[i++] = tag.removeChild(e);
return r;
}
function randthem(tag) {
var els = oldie ? tag.all : tag.getElementsByTagName('*'),
i = els.length,
childels = [];
while (--i > -1) {
if (els[i].parentNode === tag) {
childels.push(els[i]);
}
}
childels.sort(function() {
return 0.5 - Math.random();
});
i = childels.length;
while (--i > -1) {
tag.appendChild(childels[i]);
}
}
function Marq(c, tag) {
var p, u, s, a, ims, ic, i, marqContent, cObj = this;
this.mq = marqueeInit.ar[c];
if (this.mq.random) {
if (tag.getElementsByTagName && tag.getElementsByTagName('tr').length === 1 && tag.childNodes.length === 1) {
randthem(tag.getElementsByTagName('tr')[0]);
} else {
randthem(tag);
}
}
for (p in defaultconfig)
if ((this.mq.hasOwnProperty && !this.mq.hasOwnProperty(p)) || (!this.mq.hasOwnProperty && !this.mq[p]))
this.mq[p] = defaultconfig[p];
this.mq.style.width = !this.mq.style.width || isNaN(parseInt(this.mq.style.width)) ? '100%' : this.mq.style.width;
if (!tag.getElementsByTagName('img')[0])
this.mq.style.height = !this.mq.style.height || isNaN(parseInt(this.mq.style.height)) ? tag.offsetHeight + 3 + 'px' : this.mq.style.height;
else
this.mq.style.height = !this.mq.style.height || isNaN(parseInt(this.mq.style.height)) ? 'auto' : this.mq.style.height;
u = this.mq.style.width.split(/\d/);
this.cw = this.mq.style.width ? [parseInt(this.mq.style.width), u[u.length - 1]] : ['a'];
marqContent = trimTags(tag);
tag.className = tag.id = '';
tag.removeAttribute('class', 0);
tag.removeAttribute('id', 0);
if (ie)
tag.removeAttribute('className', 0);
tag.appendChild(tag.cloneNode(false));
tag.className = ['marquee', c].join('');
tag.style.overflow = 'hidden';
this.c = tag.firstChild;
this.c.appendChild(this.c.cloneNode(false));
this.c.style.visibility = 'hidden';
a = [
[req1, this.c.style],
[this.mq.style, this.c.style]
];
for (i = a.length - 1; i > -1; --i)
for (p in a[i][0])
if ((a[i][0].hasOwnProperty && a[i][0].hasOwnProperty(p)) || (!a[i][0].hasOwnProperty))
a[i][1][p.encamel()] = a[i][0][p];
this.m = this.c.firstChild;
if (this.mq.mouse === 'pause') {
this.c.onmouseover = function() {
cObj.mq.stopped = true;
};
this.c.onmouseout = function() {
cObj.mq.stopped = false;
};
}
this.m.style.position = 'absolute';
this.m.style.left = '-10000000px';
this.m.style.whiteSpace = 'nowrap';
if (ie5) this.c.firstChild.appendChild((this.m = document.createElement('nobr')));
if (!this.mq.noAddedSpace)
this.m.appendChild(document.createTextNode('\xa0'));
for (i = 0; marqContent[i]; ++i)
this.m.appendChild(marqContent[i]);
if (ie5) this.m = this.c.firstChild;
ims = this.m.getElementsByTagName('img');
if (ims.length) {
for (ic = 0, i = 0; i < ims.length; ++i) {
ims[i].style.display = 'inline';
if (!ims[i].alt && !this.mq.noAddedAlt) {
ims[i].alt = (tTRE[3].exec(ims[i].src)) || ('Image #' + [i + 1]);
if (!ims[i].title) {
ims[i].title = '';
}
}
ims[i].style.display = 'inline';
ims[i].style.verticalAlign = ims[i].style.verticalAlign || 'top';
if (typeof ims[i].complete === 'boolean' && ims[i].complete)
ic++;
else {
ims[i].onload = ims[i].onerror = function() {
if (++ic === ims.length)
cObj.setup(c);
};
}
if (ic === ims.length)
this.setup(c);
}
} else this.setup(c)
}
Marq.prototype.setup = function(c) {
if (this.mq.setup) return;
this.mq.setup = this;
var s, w, cObj = this,
exit = 10000;
if (this.c.style.height === 'auto')
this.c.style.height = this.m.offsetHeight + 4 + 'px';
this.c.appendChild(this.m.cloneNode(true));
this.m = [this.m, this.m.nextSibling];
if (typeof this.mq.initcontent === 'function') {
this.mq.initcontent.apply(this.mq, [this.m]);
}
if (this.mq.mouse === 'cursor driven') {
this.r = this.mq.neutral || 16;
this.sinc = this.mq.inc;
this.c.onmousemove = function(e) {
cObj.mq.stopped = false;
cObj.directspeed(e)
};
if (this.mq.moveatleast) {
this.mq.inc = this.mq.moveatleast;
if (this.mq.savedirection) {
if (this.mq.savedirection === 'reverse') {
this.c.onmouseout = function(e) {
if (cObj.contains(e)) return;
cObj.mq.inc = cObj.mq.moveatleast;
cObj.mq.direction = cObj.mq.direction === 'right' ? 'left' : 'right';
};
} else {
this.mq.savedirection = this.mq.direction;
this.c.onmouseout = function(e) {
if (cObj.contains(e)) return;
cObj.mq.inc = cObj.mq.moveatleast;
cObj.mq.direction = cObj.mq.savedirection;
};
}
} else
this.c.onmouseout = function(e) {
if (!cObj.contains(e)) cObj.mq.inc = cObj.mq.moveatleast;
};
} else
this.c.onmouseout = function(e) {
if (!cObj.contains(e)) cObj.slowdeath();
};
}
this.w = this.m[0].offsetWidth;
this.m[0].style.left = 0;
this.c.id = 'marq_kill_marg_bord';
this.m[0].style.top = this.m[1].style.top = Math.floor((this.c.offsetHeight - this.m[0].offsetHeight) / 2 - oldie) + 'px';
this.c.id = '';
this.c.removeAttribute('id', 0);
this.m[1].style.left = this.w + 'px';
s = this.mq.moveatleast ? Math.max(this.mq.moveatleast, this.sinc) : (this.sinc || this.mq.inc);
while (this.c.offsetWidth > this.w - s && --exit) {
w = isNaN(this.cw[0]) ? this.w - s : --this.cw[0];
if (w < 1 || this.w < Math.max(1, s)) {
break;
}
this.c.style.width = isNaN(this.cw[0]) ? this.w - s + 'px' : --this.cw[0] + this.cw[1];
}
this.c.style.visibility = 'visible';
this.runit();
}
Marq.prototype.slowdeath = function() {
var cObj = this;
if (this.mq.inc) {
this.mq.inc -= 1;
this.timer = setTimeout(function() {
cObj.slowdeath();
}, 100);
}
}
Marq.prototype.runit = function() {
var cObj = this,
d = this.mq.direction === 'right' ? 1 : -1;
if (this.mq.stopped || this.mq.stopMarquee) {
setTimeout(function() {
cObj.runit();
}, 300);
return;
}
if (this.mq.mouse != 'cursor driven')
this.mq.inc = Math.max(1, this.mq.inc);
if (d * parseInt(this.m[0].style.left) >= this.w)
this.m[0].style.left = parseInt(this.m[1].style.left) - d * this.w + 'px';
if (d * parseInt(this.m[1].style.left) >= this.w)
this.m[1].style.left = parseInt(this.m[0].style.left) - d * this.w + 'px';
this.m[0].style.left = parseInt(this.m[0].style.left) + d * this.mq.inc + 'px';
this.m[1].style.left = parseInt(this.m[1].style.left) + d * this.mq.inc + 'px';
setTimeout(function() {
cObj.runit();
}, 30 + (this.mq.addDelay || 0));
}
Marq.prototype.directspeed = function(e) {
e = e || window.event;
if (this.timer) clearTimeout(this.timer);
var c = this.c,
w = c.offsetWidth,
l = c.offsetLeft,
mp = (typeof e.pageX === 'number' ?
e.pageX : e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft) - l,
lb = (w - this.r) / 2,
rb = (w + this.r) / 2;
while ((c = c.offsetParent)) mp -= c.offsetLeft;
this.mq.direction = mp > rb ? 'left' : 'right';
this.mq.inc = Math.round((mp > rb ? (mp - rb) : mp < lb ? (lb - mp) : 0) / lb * this.sinc);
}
Marq.prototype.contains = function(e) {
if (e && e.relatedTarget) {
var c = e.relatedTarget;
if (c === this.c) return true;
while ((c = c.parentNode))
if (c === this.c) return true;
}
return false;
}
function resize() {
for (var s, w, m, i = 0; i < marqueeInit.ar.length; ++i) {
if (marqueeInit.ar[i] && marqueeInit.ar[i].setup) {
m = marqueeInit.ar[i].setup;
s = m.mq.moveatleast ? Math.max(m.mq.moveatleast, m.sinc) : (m.sinc || m.mq.inc);
m.c.style.width = m.mq.style.width;
m.cw[0] = m.cw.length > 1 ? parseInt(m.mq.style.width) : 'a';
while (m.c.offsetWidth > m.w - s) {
w = isNaN(m.cw[0]) ? m.w - s : --m.cw[0];
if (w < 1) {
break;
}
m.c.style.width = isNaN(m.cw[0]) ? m.w - s + 'px' : --m.cw[0] + m.cw[1];
}
}
}
}
function unload() {
for (var m, i = 0; i < marqueeInit.ar.length; ++i) {
if (marqueeInit.ar[i] && marqueeInit.ar[i].persist && marqueeInit.ar[i].setup) {
m = marqueeInit.ar[i].setup;
m.cookie.set(m.mq.uniqueid, m.m[0].style.left + ':' + m.m[1].style.left + ':' + m.mq.direction);
}
}
}
if (window.addEventListener) {
window.addEventListener('resize', resize, false);
window.addEventListener('unload', unload, false);
} else if (window.attachEvent) {
window.attachEvent('onresize', resize);
window.attachEvent('onunload', unload);
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="marquee" id="mycrawler">
Those confounded friars dully buzz that faltering jay. An appraising tongue acutely causes our courageous hogs. Their fitting submarines deftly break your approving improvisations. Her downcast taxonomies actually box up those disgusted turtles.
</div>
I have a strange problem where the select box options are not showing up on iPhones. When you click the select box the screen flickers but does not show any options. Any ideas ?
You can see it in action here : http://demo.elusivethemes.com/affliction/product/blue-fire-shirt/
Ive figured out its the stickysidebar thats causing the issue. Is there anyway to modify this so it only runs on screensizes over a certain width ?
// Sticky Sidebar
(function() {
var $, win;
$ = this.jQuery || window.jQuery;
win = $(window);
$.fn.stick_in_parent = function(opts) {
var doc, elm, enable_bottoming, fn, i, inner_scrolling, len, manual_spacer, offset_top, parent_selector, recalc_every, sticky_class;
if (opts == null) {
opts = {};
}
sticky_class = opts.sticky_class, inner_scrolling = opts.inner_scrolling, recalc_every = opts.recalc_every, parent_selector = opts.parent, offset_top = opts.offset_top, manual_spacer = opts.spacer, enable_bottoming = opts.bottoming;
if (offset_top == null) {
offset_top = 0;
}
if (parent_selector == null) {
parent_selector = void 0;
}
if (inner_scrolling == null) {
inner_scrolling = true;
}
if (sticky_class == null) {
sticky_class = "is_stuck";
}
doc = $(document);
if (enable_bottoming == null) {
enable_bottoming = true;
}
fn = function(elm, padding_bottom, parent_top, parent_height, top, height, el_float, detached) {
var bottomed, detach, fixed, last_pos, last_scroll_height, offset, parent, recalc, recalc_and_tick, recalc_counter, spacer, tick;
if (elm.data("sticky_kit")) {
return;
}
elm.data("sticky_kit", true);
last_scroll_height = doc.height();
parent = elm.parent();
if (parent_selector != null) {
parent = parent.closest(parent_selector);
}
if (!parent.length) {
throw "failed to find stick parent";
}
fixed = false;
bottomed = false;
spacer = manual_spacer != null ? manual_spacer && elm.closest(manual_spacer) : $("<div />");
if (spacer) {
spacer.css('position', elm.css('position'));
}
recalc = function() {
var border_top, padding_top, restore;
if (detached) {
return;
}
last_scroll_height = doc.height();
border_top = parseInt(parent.css("border-top-width"), 10);
padding_top = parseInt(parent.css("padding-top"), 10);
padding_bottom = parseInt(parent.css("padding-bottom"), 10);
parent_top = parent.offset().top + border_top + padding_top;
parent_height = parent.height();
if (fixed) {
fixed = false;
bottomed = false;
if (manual_spacer == null) {
elm.insertAfter(spacer);
spacer.detach();
}
elm.css({
position: "",
top: "",
width: "",
bottom: ""
}).removeClass(sticky_class);
restore = true;
}
top = elm.offset().top - (parseInt(elm.css("margin-top"), 10) || 0) - offset_top;
height = elm.outerHeight(true);
el_float = elm.css("float");
if (spacer) {
spacer.css({
width: elm.outerWidth(true),
height: height,
display: elm.css("display"),
"vertical-align": elm.css("vertical-align"),
"float": el_float
});
}
if (restore) {
return tick();
}
};
recalc();
if (height === parent_height) {
return;
}
last_pos = void 0;
offset = offset_top;
recalc_counter = recalc_every;
tick = function() {
var css, delta, recalced, scroll, will_bottom, win_height;
if (detached) {
return;
}
recalced = false;
if (recalc_counter != null) {
recalc_counter -= 1;
if (recalc_counter <= 0) {
recalc_counter = recalc_every;
recalc();
recalced = true;
}
}
if (!recalced && doc.height() !== last_scroll_height) {
recalc();
recalced = true;
}
scroll = win.scrollTop();
if (last_pos != null) {
delta = scroll - last_pos;
}
last_pos = scroll;
if (fixed) {
if (enable_bottoming) {
will_bottom = scroll + height + offset > parent_height + parent_top;
if (bottomed && !will_bottom) {
bottomed = false;
elm.css({
position: "fixed",
bottom: "",
top: offset
}).trigger("sticky_kit:unbottom");
}
}
if (scroll < top) {
fixed = false;
offset = offset_top;
if (manual_spacer == null) {
if (el_float === "left" || el_float === "right") {
elm.insertAfter(spacer);
}
spacer.detach();
}
css = {
position: "",
width: "",
top: ""
};
elm.css(css).removeClass(sticky_class).trigger("sticky_kit:unstick");
}
if (inner_scrolling) {
win_height = win.height();
if (height + offset_top > win_height) {
if (!bottomed) {
offset -= delta;
offset = Math.max(win_height - height, offset);
offset = Math.min(offset_top, offset);
if (fixed) {
elm.css({
top: offset + "px"
});
}
}
}
}
} else {
if (scroll > top) {
fixed = true;
css = {
position: "fixed",
top: offset
};
css.width = elm.css("box-sizing") === "border-box" ? elm.outerWidth() + "px" : elm.width() + "px";
elm.css(css).addClass(sticky_class);
if (manual_spacer == null) {
elm.after(spacer);
if (el_float === "left" || el_float === "right") {
spacer.append(elm);
}
}
elm.trigger("sticky_kit:stick");
}
}
if (fixed && enable_bottoming) {
if (will_bottom == null) {
will_bottom = scroll + height + offset > parent_height + parent_top;
}
if (!bottomed && will_bottom) {
bottomed = true;
if (parent.css("position") === "static") {
parent.css({
position: "relative"
});
}
return elm.css({
position: "absolute",
bottom: padding_bottom,
top: "auto"
}).trigger("sticky_kit:bottom");
}
}
};
recalc_and_tick = function() {
recalc();
return tick();
};
detach = function() {
detached = true;
win.off("touchmove", tick);
win.off("scroll", tick);
win.off("resize", recalc_and_tick);
$(document.body).off("sticky_kit:recalc", recalc_and_tick);
elm.off("sticky_kit:detach", detach);
elm.removeData("sticky_kit");
elm.css({
position: "",
bottom: "",
top: "",
width: ""
});
parent.position("position", "");
if (fixed) {
if (manual_spacer == null) {
if (el_float === "left" || el_float === "right") {
elm.insertAfter(spacer);
}
spacer.remove();
}
return elm.removeClass(sticky_class);
}
};
win.on("touchmove", tick);
win.on("scroll", tick);
win.on("resize", recalc_and_tick);
$(document.body).on("sticky_kit:recalc", recalc_and_tick);
elm.on("sticky_kit:detach", detach);
return setTimeout(tick, 0);
};
for (i = 0, len = this.length; i < len; i++) {
elm = this[i];
fn($(elm));
}
return this;
};
}).call(this);
Many thanks,
Scott
The problem is that the included error is showing in the console. Can someone help me understand why this is happening? I started learning jQuery a while back, but am still very new. Please help point me in the right direction.
"Dimensions: jQuery collection is empty"
(function($) {
var height = $.fn.height,
width = $.fn.width;
$.fn.extend({
height: function() {
if (!this[0]) error();
if (this[0] == window)
if (($.browser.mozilla || $.browser.opera) && $(document).width() > self.innerWidth) return self.innerHeight - getScrollbarWidth();
else
return self.innerHeight || $.boxModel && document.documentElement.clientHeight || document.body.clientHeight;
if (this[0] == document) return Math.max(document.body.scrollHeight, document.body.offsetHeight);
return height.apply(this, arguments);
},
width: function() {
if (!this[0]) error();
if (this[0] == window)
if (($.browser.mozilla || $.browser.opera) && $(document).height() > self.innerHeight) return self.innerWidth - getScrollbarWidth();
else
return self.innerWidth || $.boxModel && document.documentElement.clientWidth || document.body.clientWidth;
if (this[0] == document)
if ($.browser.mozilla) {
var scrollLeft = self.pageXOffset;
self.scrollTo(99999999, self.pageYOffset);
var scrollWidth = self.pageXOffset;
self.scrollTo(scrollLeft, self.pageYOffset);
return document.body.offsetWidth + scrollWidth;
} else
return Math.max(document.body.scrollWidth, document.body.offsetWidth);
return width.apply(this, arguments);
},
innerHeight: function() {
if (!this[0]) error();
return this[0] == window || this[0] == document ? this.height() : this.is(':visible') ? this[0].offsetHeight - num(this, 'borderTopWidth') - num(this, 'borderBottomWidth') : this.height() + num(this, 'paddingTop') + num(this, 'paddingBottom');
},
innerWidth: function() {
if (!this[0]) error();
return this[0] == window || this[0] == document ? this.width() : this.is(':visible') ? this[0].offsetWidth - num(this, 'borderLeftWidth') - num(this, 'borderRightWidth') : this.width() + num(this, 'paddingLeft') + num(this, 'paddingRight');
},
outerHeight: function(options) {
if (!this[0]) error();
options = $.extend({
margin: false
}, options || {});
return this[0] == window || this[0] == document ? this.height() : this.is(':visible') ? this[0].offsetHeight + (options.margin ? (num(this, 'marginTop') + num(this, 'marginBottom')) : 0) : this.height() + num(this, 'borderTopWidth') + num(this, 'borderBottomWidth') + num(this, 'paddingTop') + num(this, 'paddingBottom') + (options.margin ? (num(this, 'marginTop') + num(this, 'marginBottom')) : 0);
},
outerWidth: function(options) {
if (!this[0]) error();
options = $.extend({
margin: false
}, options || {});
return this[0] == window || this[0] == document ? this.width() : this.is(':visible') ? this[0].offsetWidth + (options.margin ? (num(this, 'marginLeft') + num(this, 'marginRight')) : 0) : this.width() + num(this, 'borderLeftWidth') + num(this, 'borderRightWidth') + num(this, 'paddingLeft') + num(this, 'paddingRight') + (options.margin ? (num(this, 'marginLeft') + num(this, 'marginRight')) : 0);
},
scrollLeft: function(val) {
if (!this[0]) error();
if (val != undefined) return this.each(function() {
if (this == window || this == document) window.scrollTo(val, $(window).scrollTop());
else
this.scrollLeft = val;
});
if (this[0] == window || this[0] == document) return self.pageXOffset || $.boxModel && document.documentElement.scrollLeft || document.body.scrollLeft;
return this[0].scrollLeft;
},
scrollTop: function(val) {
if (!this[0]) error();
if (val != undefined) return this.each(function() {
if (this == window || this == document) window.scrollTo($(window).scrollLeft(), val);
else
this.scrollTop = val;
});
if (this[0] == window || this[0] == document) return self.pageYOffset || $.boxModel && document.documentElement.scrollTop || document.body.scrollTop;
return this[0].scrollTop;
},
position: function(returnObject) {
return this.offset({
margin: false,
scroll: false,
relativeTo: this.offsetParent()
}, returnObject);
},
offset: function(options, returnObject) {
if (!this[0]) error();
var x = 0,
y = 0,
sl = 0,
st = 0,
elem = this[0],
parent = this[0],
op, parPos, elemPos = $.css(elem, 'position'),
mo = $.browser.mozilla,
ie = $.browser.msie,
oa = $.browser.opera,
sf = $.browser.safari,
sf3 = $.browser.safari && parseInt($.browser.version) > 520,
absparent = false,
relparent = false,
options = $.extend({
margin: true,
border: false,
padding: false,
scroll: true,
lite: false,
relativeTo: document.body
}, options || {});
if (options.lite) return this.offsetLite(options, returnObject);
if (options.relativeTo.jquery) options.relativeTo = options.relativeTo[0];
if (elem.tagName == 'BODY') {
x = elem.offsetLeft;
y = elem.offsetTop;
if (mo) {
x += num(elem, 'marginLeft') + (num(elem, 'borderLeftWidth') * 2);
y += num(elem, 'marginTop') + (num(elem, 'borderTopWidth') * 2);
} else
if (oa) {
x += num(elem, 'marginLeft');
y += num(elem, 'marginTop');
} else
if ((ie && jQuery.boxModel)) {
x += num(elem, 'borderLeftWidth');
y += num(elem, 'borderTopWidth');
} else
if (sf3) {
x += num(elem, 'marginLeft') + num(elem, 'borderLeftWidth');
y += num(elem, 'marginTop') + num(elem, 'borderTopWidth');
}
} else {
do {
parPos = $.css(parent, 'position');
x += parent.offsetLeft;
y += parent.offsetTop;
if (mo || ie || sf3) {
x += num(parent, 'borderLeftWidth');
y += num(parent, 'borderTopWidth');
if (mo && parPos == 'absolute') absparent = true;
if (ie && parPos == 'relative') relparent = true;
}
op = parent.offsetParent || document.body;
if (options.scroll || mo) {
do {
if (options.scroll) {
sl += parent.scrollLeft;
st += parent.scrollTop;
}
if (oa && ($.css(parent, 'display') || '').match(/table-row|inline/)) {
sl = sl - ((parent.scrollLeft == parent.offsetLeft) ? parent.scrollLeft : 0);
st = st - ((parent.scrollTop == parent.offsetTop) ? parent.scrollTop : 0);
}
if (mo && parent != elem && $.css(parent, 'overflow') != 'visible') {
x += num(parent, 'borderLeftWidth');
y += num(parent, 'borderTopWidth');
}
parent = parent.parentNode;
} while (parent != op);
}
parent = op;
if (parent == options.relativeTo && !(parent.tagName == 'BODY' || parent.tagName == 'HTML')) {
if (mo && parent != elem && $.css(parent, 'overflow') != 'visible') {
x += num(parent, 'borderLeftWidth');
y += num(parent, 'borderTopWidth');
}
if (((sf && !sf3) || oa) && parPos != 'static') {
x -= num(op, 'borderLeftWidth');
y -= num(op, 'borderTopWidth');
}
break;
}
if (parent.tagName == 'BODY' || parent.tagName == 'HTML') {
if (((sf && !sf3) || (ie && $.boxModel)) && elemPos != 'absolute' && elemPos != 'fixed') {
x += num(parent, 'marginLeft');
y += num(parent, 'marginTop');
}
if (sf3 || (mo && !absparent && elemPos != 'fixed') || (ie && elemPos == 'static' && !relparent)) {
x += num(parent, 'borderLeftWidth');
y += num(parent, 'borderTopWidth');
}
break;
}
} while (parent);
}
var returnValue = handleOffsetReturn(elem, options, x, y, sl, st);
if (returnObject) {
$.extend(returnObject, returnValue);
return this;
} else {
return returnValue;
}
},
offsetLite: function(options, returnObject) {
if (!this[0]) error();
var x = 0,
y = 0,
sl = 0,
st = 0,
parent = this[0],
offsetParent, options = $.extend({
margin: true,
border: false,
padding: false,
scroll: true,
relativeTo: document.body
}, options || {});
if (options.relativeTo.jquery) options.relativeTo = options.relativeTo[0];
do {
x += parent.offsetLeft;
y += parent.offsetTop;
offsetParent = parent.offsetParent || document.body;
if (options.scroll) {
do {
sl += parent.scrollLeft;
st += parent.scrollTop;
parent = parent.parentNode;
} while (parent != offsetParent);
}
parent = offsetParent;
} while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML' && parent != options.relativeTo);
var returnValue = handleOffsetReturn(this[0], options, x, y, sl, st);
if (returnObject) {
$.extend(returnObject, returnValue);
return this;
} else {
return returnValue;
}
},
offsetParent: function() {
if (!this[0]) error();
var offsetParent = this[0].offsetParent;
while (offsetParent && (offsetParent.tagName != 'BODY' && $.css(offsetParent, 'position') == 'static')) offsetParent = offsetParent.offsetParent;
return $(offsetParent);
}
});
var error = function() {
throw "Dimensions: jQuery collection is empty";
};
var num = function(el, prop) {
return parseInt($.css(el.jquery ? el[0] : el, prop)) || 0;
};
var handleOffsetReturn = function(elem, options, x, y, sl, st) {
if (!options.margin) {
x -= num(elem, 'marginLeft');
y -= num(elem, 'marginTop');
}
if (options.border && (($.browser.safari && parseInt($.browser.version) < 520) || $.browser.opera)) {
x += num(elem, 'borderLeftWidth');
y += num(elem, 'borderTopWidth');
} else if (!options.border && !(($.browser.safari && parseInt($.browser.version) < 520) || $.browser.opera)) {
x -= num(elem, 'borderLeftWidth');
y -= num(elem, 'borderTopWidth');
}
if (options.padding) {
x += num(elem, 'paddingLeft');
y += num(elem, 'paddingTop');
}
if (options.scroll && (!$.browser.opera || elem.offsetLeft != elem.scrollLeft && elem.offsetTop != elem.scrollLeft)) {
sl -= elem.scrollLeft;
st -= elem.scrollTop;
}
return options.scroll ? {
top: y - st,
left: x - sl,
scrollTop: st,
scrollLeft: sl
} : {
top: y,
left: x
};
};
var scrollbarWidth = 0;
var getScrollbarWidth = function() {
if (!scrollbarWidth) {
var testEl = $('<div>').css({
width: 100,
height: 100,
overflow: 'auto',
position: 'absolute',
top: -1000,
left: -1000
}).appendTo('body');
scrollbarWidth = 100 - testEl.append('<div>').find('div').css({
width: '100%',
height: 200
}).width();
testEl.remove();
}
return scrollbarWidth;
};
})(jQuery);
I think you want to verify that this[0] having value or not, or it may be empty.
try to use $.isEmptyObject provided by jquery
ex:
if($.isEmptyObject(this[0])){
error();
}
The error function is being called when (!this[0]) is true.
This means that the object that you're using should be an array, and the first element should exist.
this[0] is the first element of the array.
this[0] evaluates to true if the object exists.
!(this[0]) evaluates to true if the object doesn't exist.
I have the following script and am trying to add mouse enter and leave events on a slideshow such that when the mouse is over the image it won't switch to the next one, and once removed it continues.
I can get the slide to stop when the mouse is over but once the mouse is out the slideshow won't proceed.
I am unsure if these 2 lines are in the right place:
---> jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
---> jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
jQuery(function () {
jQuery('a').focus(function () {
this.blur();
});
SI.Files.stylizeAll();
slider.init();
});
---> var MOUSE_IN = false;
var slider = {
num: -1,
cur: 0,
cr: [],
al: null,
at: 10 * 1000, /* change 1000 to control speed*/
ar: true,
anim:'slide',
fade_speed:600,
init: function () {
if (!slider.data || !slider.data.length) return false;
var d = slider.data;
slider.num = d.length;
var pos = Math.floor(Math.random() * 1);
for (var i = 0; i < slider.num; i++) {
if(slider.anim == 'fade')
{
jQuery('#' + d[i].id).hide();
}
else{
jQuery('#' + d[i].id).css({
left: ((i - pos) * 1000)
});
}
jQuery('#slide-nav').append('<a id="slide-link-' + i + '" href="#" onclick="slider.slide(' + i + ');return false;" onfocus="this.blur();">' + (i + 1) + '</a>');
}
jQuery('img,div#slide-controls', jQuery('div#slide-holder')).fadeIn();
---> jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
---> jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
slider.text(d[pos]);
slider.on(pos);
if(slider.anim == 'fade')
{
slider.cur = -1;
slider.slide(0);
}
else{
slider.cur = pos;
window.setTimeout('slider.auto();', slider.at);
}
},
auto: function () {
if (!slider.ar) return false;
if(MOUSE_IN) return false;
var next = slider.cur + 1;
if (next >= slider.num) next = 0;
slider.slide(next);
},
slide: function (pos) {
if (pos < 0 || pos >= slider.num || pos == slider.cur) return;
window.clearTimeout(slider.al);
slider.al = window.setTimeout('slider.auto();', slider.at);
var d = slider.data;
if(slider.anim == 'fade')
{
for (var i = 0; i < slider.num; i++) {
if(i == slider.cur || i == pos) continue;
jQuery('#' + d[i].id).hide();
}
if(slider.cur != -1){
jQuery('#' + d[slider.cur].id).stop(false,true);
jQuery('#' + d[slider.cur].id).fadeOut(slider.fade_speed);
jQuery('#' + d[pos].id).fadeIn(slider.fade_speed);
}
else
{
jQuery('#' + d[pos].id).fadeIn(slider.fade_speed);
}
}
else
{
for (var i = 0; i < slider.num; i++)
jQuery('#' + d[i].id).stop().animate({
left: ((i - pos) * 1000)
},
1000, 'swing');
}
slider.on(pos);
slider.text(d[pos]);
slider.cur = pos;
},
on: function (pos) {
jQuery('#slide-nav a').removeClass('on');
jQuery('#slide-nav a#slide-link-' + pos).addClass('on');
},
text: function (di) {
slider.cr['a'] = di.client;
slider.cr['b'] = di.desc;
slider.ticker('#slide-client span', di.client, 0, 'a');
slider.ticker('#slide-desc', di.desc, 0, 'b');
},
ticker: function (el, text, pos, unique) {
if (slider.cr[unique] != text) return false;
ctext = text.substring(0, pos) + (pos % 2 ? '-' : '_');
jQuery(el).html(ctext);
if (pos == text.length) jQuery(el).html(text);
else window.setTimeout('slider.ticker("' + el + '","' + text + '",' + (pos + 1) + ',"' + unique + '");', 30);
}
};
if (!window.SI) {
var SI = {};
};
SI.Files = {
htmlClass: 'SI-FILES-STYLIZED',
fileClass: 'file',
wrapClass: 'cabinet',
fini: false,
able: false,
init: function () {
this.fini = true;
var ie = 0
if (window.opera || (ie && ie < 5.5) || !document.getElementsByTagName) {
return;
}
this.able = true;
var html = document.getElementsByTagName('html')[0];
html.className += (html.className != '' ? ' ' : '') + this.htmlClass;
},
stylize: function (elem) {
if (!this.fini) {
this.init();
};
if (!this.able) {
return;
};
elem.parentNode.file = elem;
elem.parentNode.onmousemove = function (e) {
if (typeof e == 'undefined') e = window.event;
if (typeof e.pageY == 'undefined' && typeof e.clientX == 'number' && document.documentElement) {
e.pageX = e.clientX + document.documentElement.scrollLeft;
e.pageY = e.clientY + document.documentElement.scrollTop;
};
var ox = oy = 0;
var elem = this;
if (elem.offsetParent) {
ox = elem.offsetLeft;
oy = elem.offsetTop;
while (elem = elem.offsetParent) {
ox += elem.offsetLeft;
oy += elem.offsetTop;
};
};
var x = e.pageX - ox;
var y = e.pageY - oy;
var w = this.file.offsetWidth;
var h = this.file.offsetHeight;
this.file.style.top = y - (h / 2) + 'px';
this.file.style.left = x - (w - 30) + 'px';
};
},
stylizeById: function (id) {
this.stylize(document.getElementById(id));
},
stylizeAll: function () {
if (!this.fini) {
this.init();
};
if (!this.able) {
return;
};
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass) != -1) this.stylize(input);
};
}
};
(function (jQuery) {
jQuery.fn.pngFix = function (settings) {
settings = jQuery.extend({
blankgif: 'blank.gif'
},
settings);
var ie55 = (navigator.appName == 'Microsoft Internet Explorer' && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf('MSIE 5.5') != -1);
var ie6 = (navigator.appName == 'Microsoft Internet Explorer' && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf('MSIE 6.0') != -1);
if (jQuery.browser.msie && (ie55 || ie6)) {
jQuery(this).each(function () {
var bgIMG = jQuery(this).css('background-image');
if (bgIMG.indexOf(".png") != -1) {
var iebg = bgIMG.split('url("')[1].split('")')[0];
jQuery(this).css('background-image', 'none');
jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='" + settings.sizingMethod + "')";
}
});
}
return jQuery;
};
})(jQuery);
jQuery(function () {
if (jQuery.browser.msie && jQuery.browser.version < 7) {
}
});
The position of both lines is fine, they just add an event handler to the mouse in/out event. The problem you experience is actually in tha auto function, if you note, at the end of the init function you have:
window.setTimeout('slider.auto();', slider.at)
This line makes a call to the auto function after a slider.at time (which is 10 seconds in your example), the auto function checks if MOUSE_IN is set to true, if it's not, then calls the slide function, then in the slide function you have another call to the auto function:
slider.al = window.setTimeout('slider.auto();', slider.at);
But once you set the MOUSE_IN variable to true the auto function simply returns and it stop the execution of further slide functions, to solve this, you may want to either handle the MOUSE_IN logic in the slide function, or before returning false in the auto function, call with a time out the auto function again.
Thought this would work but it doesnt, the mouseleave eventdoesnt seem to fire.
jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
while(MOUSE_IN==true)
{
jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
}