This has been asked before and I got my code running.
The problem is with some weird viewport sizes the script seems to freeze.
There is nothing you can do but kill the tab.
I tried to script some backup that will kill the loop if its frozen, but it does not seem to get the job done.
Can anyone tell me whats wrong? Or show me an error in the script in general thats causing the freeze?
Thats the site where the code is running:
http://unkn0wn3d.com
JS Code is eithere there:
http://unkn0wn3d.com/css/pos.js
or here:
var pos = function(){
var containerW = $("article").width();
var containerH = $("article").height();
var langH = parseInt($( ".languages" ).position().top + $( ".languages" ).height());
var langW = parseInt($( ".languages" ).position().left + $( ".languages" ).width());
var creditW = parseInt($( ".credit" ).position().left - $(".link:first").width() + 15);
var positions = [];
var froze = false;
setTimeout(function(){froze=true;}, 2000)
$('.link').each(function() {
var coords = {
w: $(this).outerWidth(true)+5,
h: $(this).outerHeight(true)+5
};
var success = false;
while (!success)
{
coords.x = parseInt(Math.random() * (containerW-coords.w));
coords.y = parseInt(Math.random() * (containerH-coords.h));
var success = true;
$.each(positions, function(){
if (froze){return false;}
if (
(coords.x <= langW &&
coords.y <= langH) ||
(coords.x >= creditW &&
coords.y <= langH) ||
(coords.x <= (this.x + this.w) &&
(coords.x + coords.w) >= this.x &&
coords.y <= (this.y + this.h) &&
(coords.y + coords.h) >= this.y)
)
{
success = false;
}
});
}
positions.push(coords);
$(this).css({
top: coords.y + 'px',
left: coords.x + 'px',
display: 'block'
});
})};
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = "Don't call this twice without a uniqueId";
}
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
$(document).ready(
pos()
);
$(window).resize(function () {
waitForFinalEvent(function(){pos();}, 500, "resize");
});
You have 2 problems. I don't see where you are doing it, but the size of your A.link elements is being controlled only by the height of the viewport. So if the viewport is tall and narrow, then the links are large, and it's simply impossible to fit them all.
The second problem is that if the links can't be placed your code just keeps trying forever. The timer will never fire because the main script is still busy running. Rather than just do
while (!success)
it would be better to do a limited number of attempts:
var success = false;
for (var attempt = 0; !success && attempt < 50; attempt++)
{
....
}
By limiting the number of tries it will stop it freezing, even if the links are left overlapping. Then you can remove froze and the timer.
Even better would be to introduce a tolerance as the number of attempts increases - so they are allowed to overlap a little bit.
Your while loop never terminates since inside it you wrote var success = true
You redefined your success variable again by using var, so now you have 2 instances of success and the first one is never set to true so the loop never terminates. Try removing var from var success = true
Related
So what im trying to do in general is -> get a moment when user scrolls up really fast on mobile device -> some text executed in console (for example)
What I have is 2 simple functions:
//calculate scroll speed
var mobileScroll = (function(){
var last_position, new_position, timer, delta, delay = 50;
function clear() {
last_position = null;
delta = 0;
}
clear();
return function(){
new_position = window.scrollY;
if ( last_position !== null ){
delta = new_position - last_position;
}
last_position = new_position;
clearTimeout(timer);
timer = setTimeout(clear, delay);
return delta;
};
})();
Then I'm trying to compare the outputted value with some static number like this:
var scrolledFast = function scrolledFast(e) {
console.log("scroll: " + mobileScroll());//works fine
console.log(mobileScroll());//always 0
//if statement does not work
if(document.body.classList.contains('on-mobile-device') && mobileScroll() < -200 ){
console.log('Scrolled up fast enough');
}
}
document.addEventListener('scroll', scrolledFast);
The problem is that I don't understand why I can get the outputted value like this:
console.log("scroll speed: " + mobileScroll()); // I see "scroll: -100" or some other value
But when I'm trying to get something like:
console.log(mobileScroll());
//or
var mobScrollSpeed = mobileScroll();
console.log(mobScrollSpeed);
it is always 0...
I have been trying to make a simple "smoothscroll" function using location.href that triggers on the mousewheel. The main problem is that the EventListener(wheel..) gets a bunch of inputs over the span of ca. 0,9 seconds which keeps triggering the function. "I only want the function to run once".
In the code below I have tried to remove the eventlistener as soon as the function runs, which actually kinda work, the problem is that I want it to be added again, hence the timed function at the bottom. This also kinda work but I dont want to wait a full second to be able to scroll and if I set it to anything lover the function will run multiple times.
I've also tried doing it with conditions "the commented out true or false variables" which works perfectly aslong as you are only scrolling up and down but you cant scroll twice or down twice.
window.addEventListener('wheel', scrolltest, true);
function scrolltest(event) {
window.removeEventListener('wheel', scrolltest, true);
i = event.deltaY;
console.log(i);
if (webstate == 0) {
if (i < 0 && !upexecuted) {
// upexecuted = true;
location.href = "#forside";
// downexecuted = false;
} else if (i > 0 && !downexecuted) {
// downexecuted = true;
location.href = "#underside";
// upexecuted = false;
}
}
setTimeout(function(){ window.addEventListener('wheel', scrolltest, true); }, 1000);
}
I had hoped there was a way to stop the wheel from constantly produce inputs over atleast 0.9 seconds.
"note: don't know if it can help in some way but when the browser is not clicked (the active window) the wheel will registre only one value a nice 100 for down and -100 for up"
What you're trying to do is called "debouncing" or "throttling". (Those aren't exactly the same thing, but you can look up the difference in case it's going to matter to you.) Functions for this are built into libraries like lodash, but if using a library like that is too non-vanilla for what you have in mind, you can always define your own debounce function: https://www.geeksforgeeks.org/debouncing-in-javascript/
You might also want to look into requestanimationframe.
a different approach
okey after fiddeling with this for just about 2 days i got fustrated and started over. no matter what i did the browsers integrated "glide-scroll" was messing up the event trigger. anyway i decided to animate the scrolling myself and honestly it works better than i had imagined: here is my code if anyone want to do this:
var body = document.getElementsByTagName("BODY")[0];
var p1 = document.getElementById('page1');
var p2 = document.getElementById('page2');
var p3 = document.getElementById('page3');
var p4 = document.getElementById('page4');
var p5 = document.getElementById('page5');
var whatpage = 1;
var snap = 50;
var i = 0;
// this part is really just to read what "page" you are on if you update the site. if you add more pages you should remember to add it here too.
window.onload = setcurrentpage;
function setcurrentpage() {
if (window.pageYOffset == p1.offsetTop) {
whatpage = 1;
} else if (window.pageYOffset == p2.offsetTop) {
whatpage = 2;
} else if (window.pageYOffset == p3.offsetTop) {
whatpage = 3;
} else if (window.pageYOffset == p4.offsetTop) {
whatpage = 4;
} else if (window.pageYOffset == p5.offsetTop) {
whatpage = 5;
}
}
// this code is designet to automaticly work with any "id" you have aslong as you give it a variable called p"number" fx p10 as seen above.
function smoothscroll() {
var whatpagenext = whatpage+1;
var whatpageprev = whatpage-1;
var currentpage = window['p'+whatpage];
var nextpage = window['p'+whatpagenext];
var prevpage = window['p'+whatpageprev];
console.log(currentpage);
if (window.pageYOffset > currentpage.offsetTop + snap && window.pageYOffset < nextpage.offsetTop - snap){
body.style.overflowY = "hidden";
i++
window.scrollTo(0, window.pageYOffset+i);
if (window.pageYOffset <= nextpage.offsetTop + snap && window.pageYOffset >= nextpage.offsetTop - snap) {
i=0;
window.scrollTo(0, nextpage.offsetTop);
whatpage += 1;
body.style.overflowY = "initial";
}
} else if (window.pageYOffset < currentpage.offsetTop - snap && window.pageYOffset > prevpage.offsetTop + snap){
body.style.overflowY = "hidden";
i--
window.scrollTo(0, window.pageYOffset+i);
if (window.pageYOffset >= prevpage.offsetTop - snap && window.pageYOffset <= prevpage.offsetTop + snap) {
i=0;
window.scrollTo(0, prevpage.offsetTop);
whatpage -= 1;
body.style.overflowY = "initial";
}
}
}
to remove the scrollbar completely just add this to your stylesheet:
::-webkit-scrollbar {
width: 0px;
background: transparent;
}
I'm trying to have a bunch of variables reset themselves on a resize (I'm just a little crazy like that. Yes, I know virtually no one will do it as their using the page). I want to be able to have the plugin that I created (hScroll) reset it's variables when the user resizes the page. I only want to declare them and set them within one line, so I tried using the window.variableName = ... but that didn't seem to work. Once again, all I want to be able to do is have to declare and set the variable within one line, and on resize, have the variables reestablish themselves, since a few are size dependent. As you can see, I have also tried the triggerHandler method as well, but it does not seem to be working.
(function($) {
$.fn.extend({
hScroll: function(options) {
var defaults = {
container: "nav",
sliderName: ".sliderName",
partContainer: ".beep"
};
var o = $.extend(defaults, options);
return this.each(function() {
// I want to set global variables and have them reset... START
var slider = $(o.container + " " + o.sliderName),
sliderWidth = slider.outerWidth(),
container = $(o.container),
containerWidth = container.outerWidth(),
containerInnerWidth = containerWidth - (2 * parseInt(container.css("padding-left"))),
sliderPieces = slider.children(o.partContainer),
numberOfPieces = sliderPieces.length,
containerWidth = $(o.container).width(),
piecesWidth = 0;
// set slide widths
if (containerInnerWidth > sliderWidth / numberOfPieces) {
piecesWidth = sliderWidth / numberOfPieces
} else {
piecesWidth = containerInnerWidth;
}
sliderPieces.width(piecesWidth);
// set gutter and how many pieces can be seen at once.
var wholePiecesSeen = Math.floor(containerInnerWidth / piecesWidth),
gutter = parseInt((containerInnerWidth - (wholePiecesSeen * piecesWidth)) / 2);
// END - I want this block to be reset when the window is resized.
var isContainerBigEnough = function() {
if (containerInnerWidth > sliderWidth) {
$(o.container).removeClass("tooBig");
} else {
$(o.container).addClass("tooBig");
}
}
isContainerBigEnough();
// arrow variables
$(o.container + " .previous").click(function() {
var addOn = 0,
newPosition = 0,
thisFarGone = parseInt(slider.css("left")),
moveThisFar = piecesWidth,
allTheWay = containerInnerWidth - sliderWidth;
// always make sure to center your tiles
if (thisFarGone == allTheWay) {
moveThisFar = moveThisFar - gutter;
console.log(moveThisFar);
console.log("in");
};
newPosition = -thisFarGone - moveThisFar;
//make sure it doesn't go too far
if (newPosition < 0) {
newPosition = 0;
}
newPosition = parseInt(newPosition); // - addOn);
slider.css({
"left": (-newPosition) + "px"
});
});
$(o.container + " .next").click(function() {
var addOn = 0,
newPosition = 0,
thisFarGone = parseInt(slider.css("left")),
moveThisFar = piecesWidth;
// always make sure to center your tiles
if (thisFarGone == 0 ||
thisFarGone == -0 ||
thisFarGone == undefined) {
moveThisFar = moveThisFar - gutter;
};
newPosition = moveThisFar - thisFarGone;
//make sure it doesn't go too far
if (newPosition > sliderWidth - containerInnerWidth) {
newPosition = sliderWidth - containerInnerWidth;
}
newPosition = parseInt(newPosition); // - addOn);
slider.css({
"left": (-newPosition) + "px"
});
});
$(window).resize(function() {
console.log("working");
$(o.container).triggerHandler("hScroll");
});
});
}
});
})(jQuery);
$(document).ready(function() {
$(".posts-timeline").hScroll({
container: ".posts-timeline",
sliderName: "#slider",
partContainer: ".post"
});
});
Something like this?
console.log("working");
$(o.container).hScroll("hScroll");
Maybe not exactly that, but if you want those variables to be reassigned, I'm guessing that would wind up being done somewhere in $(window).resize(function() {
This question already has answers here:
Animate counter when in viewport
(4 answers)
Closed 6 years ago.
I'm trying to make a number count up when it's within the viewport, but currently, the script i'm using will interrupt the count on scroll.
How would I make it so that it will ignore the scroll and just count up when it's within the viewport? This needs to work on mobile, so even when a user is scrolling on touch. It cannot interrupt the count.
Please see here:
http://jsfiddle.net/Q37Q6/27/
(function ($) {
$.fn.visible = function (partial, hidden) {
var $t = $(this).eq(0),
t = $t.get(0),
$w = $(window),
viewTop = $w.scrollTop(),
viewBottom = viewTop + $w.height(),
_top = $t.offset().top,
_bottom = _top + $t.height(),
compareTop = partial === true ? _bottom : _top,
compareBottom = partial === true ? _top : _bottom,
clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;
return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop));
};
})(jQuery);
// Scrolling Functions
$(window).scroll(function (event) {
function padNum(num) {
if (num < 10) {
return "" + num;
}
return num;
}
var first = 25; // Count up to 25x for first
var second = 4; // Count up to 4x for second
function countStuffUp(points, selector, duration) { //Animate count
$({
countNumber: $(selector).text()
}).animate({
countNumber: points
}, {
duration: duration,
easing: 'linear',
step: function () {
$(selector).text(padNum(parseInt(this.countNumber)));
},
complete: function () {
$(selector).text(points);
}
});
}
// Output to div
$(".first-count").each(function (i, el) {
var el = $(el);
if (el.visible(true)) {
countStuffUp(first, '.first-count', 1600);
}
});
// Output to div
$(".second-count").each(function (i, el) {
var el = $(el);
if (el.visible(true)) {
countStuffUp(second, '.second-count', 1000);
}
});
});
Your example is more complicated than you're aware, I think. You're doing things in a pretty unusual way, here, using a jQuery animate method on a custom property as your counter. It's kind of cool, but it also makes things a little more complicated. I've had to add a number of things to straighten up the situation.
I went ahead and rewrote your visible plugin, largely because I had no idea what yours was doing. This one's simple!
When your counters become visible, they get a "counting" class so that the counter isn't re-fired on them when they're already counting.
I save a reference to the object you have your custom counter animation on to the data attribute of the counter. This is vital: without that reference, you can't stop the animation when it goes offscreen.
I do some fanciness inside the step function to keep track of how much time is left so that you can keep your counter running at the same speed even if it stops and starts. If your counter runs for half a second and it's set to use one second for the whole animation, if it gets interrupted and restarted you only want to set it to half a second when you restart the counter.
http://jsfiddle.net/nate/p9wgx/1/
(function ($) {
$.fn.visible = function () {
var $element = $(this).eq(0),
$win = $(window),
elemTop = $element.position().top,
elemBottom = elemTop + $element.height(),
winTop = $win.scrollTop(),
winBottom = winTop + $win.height();
if (elemBottom < winTop) {
return false;
} else if (elemTop > winBottom) {
return false;
} else {
return true;
}
};
})(jQuery);
function padNum(num) {
if (num < 10) {
return " " + num;
}
return num;
}
var $count1 = $('.first-count');
var $count2 = $('.second-count');
// Scrolling Functions
$(window).scroll(function (event) {
var first = 25; // Count up to 25x for first
var second = 4; // Count up to 4x for second
function countStuffUp(points, selector, duration) {
//Animate count
var $selector = $(selector);
$selector.addClass('counting');
var $counter = $({
countNumber: $selector.text()
}).animate({
countNumber: points
}, {
duration: duration,
easing: 'linear',
step: function (now) {
$selector.data('remaining', (points - now) * (duration / points));
$selector.text(padNum(parseInt(this.countNumber)));
},
complete: function () {
$selector.removeClass('counting');
$selector.text(points);
}
});
$selector.data('counter', $counter);
}
// Output to div
$(".first-count").each(function (i, el) {
var el = $(el);
if (el.visible() && !el.hasClass('counting')) {
var duration = el.data('remaining') || 1600;
countStuffUp(first, '.first-count', duration);
} else if (!el.visible() && el.hasClass('counting')) {
el.data('counter').stop();
el.removeClass('counting');
}
});
// Output to div
$(".second-count").each(function (i, el) {
var el = $(el);
if (el.visible() && !el.hasClass('counting')) {
var duration = el.data('remaining') || 1000;
countStuffUp(second, '.second-count', duration);
} else if (!el.visible() && el.hasClass('counting')) {
el.data('counter').stop();
el.removeClass('counting');
}
});
});
There's a lot here. Feel free to ask me questions if anything's not clear.
I am trying to scroll by highlighting text and dragging down. Now, as you are probably aware, this is standard, default behavior for a standard overflow: auto element, however I am trying to do it with some fancy scrollbars courtesy of jQuery jScrollPane by Kelvin Luck.
I have created a fiddle here: DEMO
basically as you can see, highlighting and scrolling works in the top box (the default overflow: auto box) but in the second it doesn't and, to compound matters, once you reach the bottom it INVERTS your selection!
So, my question(s) is(are) this(these): is there a way to fix this? If so, how?
UPDATE
I have been working on this quite a bit and have found a slight solution using setTimeout()
however, it doesn't work as intended and if anybody is willing to help I have forked it to a new fiddle here: jsFiddle
the code itself is:
pane = $('#scrolldiv2');
pane.jScrollPane({animateEase: 'linear'});
api = pane.data('jsp');
$('#scrolldiv2').on('mousedown', function() {
$(this).off().on('mousemove', function(e) {
rel = $(this).relativePosition();
py = e.pageY - rel.y;
$t = $(this);
if (py >= $(this).height() - 20) {
scroll = setTimeout(scrollBy, 400, 20);
}
else if (py < 20) {
scroll = setTimeout(scrollBy, 400, -20);
}
else {
clearTimeout(scroll);
}
})
}).on('mouseup', function() {
$(this).off('mousemove');
clearTimeout(scroll);
})
var scrollBy = function(v) {
if (api.getContentPositionY < 20 & v == -20) {
api.scrollByY(v + api.getContentPositionY);
clearTimeout(scroll);
} else if (((api.getContentHeight - $t.height()) - api.getContentPositionY) < 20 & v == 20) {
api.scrollByY((api.getContentHeight - $t.height()) - api.getContentPositionY);
clearTimeout(scroll);
} else {
api.scrollByY(v, true)
scroll = setTimeout(scrollBy, 400, v)
}
}
$.fn.extend({
relativePosition: function() {
var t = this.get(0),
x, y;
if (t.offsetParent) {
x = t.offsetLeft;
y = t.offsetTop;
while ((t = t.offsetParent)) {
x += t.offsetLeft;
y += t.offsetTop;
}
}
return {
x: x,
y: y
}
},
})
You just have to scroll down/up depending on how close the mouse is to the end of the div; is not as good as the native solution but it gets the job done ( http://jsfiddle.net/PWYpu/25/ )
$('#scrolldiv2').jScrollPane();
var topScroll = $('#scrolldiv2').offset().top,
endScroll = topScroll + $('#scrolldiv2').height(),
f = ($('#scrolldiv2').height() / $('#scrolldiv2 .jspPane').height())*5 ,
selection = false,
_prevY;
$(document).mousemove(function(e){
var mY;
var delta = _prevY - e.pageY;
if((e.pageY < endScroll && (mY = ((e.pageY - endScroll + 80)/f)) > 0) ||
(e.pageY > topScroll && (mY = (e.pageY - (topScroll + 80))/f) < 0)){
if(selection && (delta > 10 || delta < -10) )
$('#scrolldiv2').data('jsp').scrollByY(mY, false) ;
}
})
$('#scrolldiv2').mousedown(function(e){_prevY = e.pageY; selection = true ;})
$(window).mouseup(function(){selection = false ;})
BTW, the reason it inverts the selection is because it reached the end of the document, just put some white space down there and problem solved.
I really hate to say it, I know it's an issue even I ran into with the update to this plugin, but in the old plugin (seen here) it works just fine with basic call. So I just reverted my copy.