Here is my code:
var scrollOnLoad = function scrollOnLoad(selector, offset) {
window.onload = function() {
if ($(window).height() <= 800) {
var attempts = 100;
var interval = setInterval(function() {
var h = $(selector).height();
console.log("attempt #" + attempts + ", h=" + h);
if (h > 0 || !attempts--) {
$("body,html").animate({scrollTop : h + offset}, '1000');
clearInterval(interval);
}
}, 50)
}
}
}
and here is how its caling:
scrollOnLoad(".content-wrapper", 50);
I've noticed that window.onload event is not firing in IE (console is not logging anything) - any ideas why? Thanks in advance!
You can use document.readyState property:
function scrollOnLoad(selector, offset) {
if(document.readyState === 'complete')
x();
else
document.addEventListener('readystatechange', function(){
if(document.readyState === 'complete')
x();
});
function x(){
if ($(window).height() <= 800) {
var attempts = 100;
var interval = setInterval(function() {
var h = $(selector).height();
console.log("attempt #" + attempts + ", h=" + h);
if (h > 0 || !attempts--) {
$("body,html").animate({scrollTop : h + offset}, '1000');
clearInterval(interval);
}
}, 50)
}
}
}
As mentioned in comments your function scrollOnLoad is getting executed after the window has loaded.
Now in better scenarios these events should be added in global scope.
So it should be like
window.onload = function() {
if(someConditionIsSatisfied){
if ($(window).height() <= 800) {
var attempts = 100;
var interval = setInterval(function() {
var h = $(selector).height();
console.log("attempt #" + attempts + ", h=" + h);
if (h > 0 || !attempts--) {
$("body,html").animate({scrollTop : h + offset}, '1000');
clearInterval(interval);
}
}, 50)
}
}
}
Related
I'm trying to build a simple game and having hard time with collision detecting. I want the alert to be popped up when the hero hits the virus and below is my js code. I'm not sure if my collision detect logic is wrong too. The viruses are moving randomly and I used CSS transition for them to move gradually.
var henryLocation = {
top: 700,
left: 700
}
document.onkeydown = function (evt) {
// console.log(evt)
if (evt.keyCode === 38 && henryLocation.top > 10) {
henryLocation.top = henryLocation.top - 25
} else if (evt.keyCode === 40 && henryLocation.top < 700) {
henryLocation.top = henryLocation.top + 25
} else if (evt.keyCode === 37 && henryLocation.left > 10) {
henryLocation.left = henryLocation.left - 25
} else if (evt.keyCode === 39 && henryLocation.left < 1360) {
henryLocation.left = henryLocation.left + 25
}
moveHenry()
}
function moveHenry () {
document.getElementById('henry').style.top = henryLocation.top + 'px'
document.getElementById('henry').style.left = henryLocation.left + 'px'
}
const startBtn = document.getElementById('btn-start')
startBtn.addEventListener("click", theGame)
function theGame () {
const startGame = setInterval(moveCorona, 1300)
function moveCorona () {
const theCorona = document.getElementById('corona')
const theCorona1 = document.getElementById('corona1')
const theCorona2 = document.getElementById('corona2')
const w = 1300, h = 600
theCorona.style.top = Math.floor(Math.random() * h) + 'px'
theCorona.style.left = Math.floor(Math.random() * w) + 'px'
theCorona1.style.top = Math.floor(Math.random() * h) + 'px'
theCorona1.style.left = Math.floor(Math.random() * w) + 'px'
theCorona2.style.top = Math.floor(Math.random() * h) + 'px'
theCorona2.style.left = Math.floor(Math.random() * w) + 'px'
function collisionDetect () {
var theHenry = henry.getBoundingClientRect();
var theCorona = corona.getBoundingClientRect();
if ((theCorona.top > theHenry.top && theCorona.top < theHenry.bottom) || (theCorona.bottom > theHenry.top && theCorona.bottom < theHenry.bottom)) {
let verticalCollision = true
} else {
let verticalCollision = false
}
if ((theCorona.right > theHenry.left && theCorona.right < theHenry.right) || (theCorona.left < theHenry.right && theCorona.left > theHenry.left)) {
let horizontalCollision = true
} else {
let horizontalCollision = false
}
if (verticalCollision && horizontalCollision) {
alert('collision detected')
} else {
console.log('Game goes on')
}
}
// collisionDetect()
}
}
function gameLoop () {
setTimeout(gameLoop, 1000)
}
gameLoop()
I have a small javascript animation that shows a new dropdown select menu after the previous one has been chosen.
Heres the HTML:
<div class="steps">
<div id="step1">
<button type="button" class="button standardBtn" style="opacity: 1.5" id="toJapanese" onclick="setToJapanese(); activatePullDown()">To Japanese</button>
<button type="button" class="button standardBtn" style="opacity: 1.5" id="toWestern" onclick="setToWestern(); activatePullDown()">To Western</button>
</div>
<div id="step2" style="opacity: 0"></div>
<div id="step3" style="opacity: 0"></div>
<div id="step4" style="opacity: 0"></div>
</div>
When a button from step1 is clicked, the first menu, step2, appears. When an item from step2 is selected, it moves to the left and a new menu, step3, shows. It works in every browser except IE (10 and 11). In IE, step2 moves over correctly, but step3 fails to show.
Heres my Javascript for when step2 is selected.
function yearSelected() {
startMoveLeft('step3');
getMonths();
setTimeout(fadeIn, 600, 'step3', 'normal', 0);
}
function startMoveLeft(id) {
var element = document.getElementById(id);
var mq = window.matchMedia( "(min-width: 800px)" );
var display = [];
if (mq.matches) {
display = 'inline-block';
}
else {
display = 'block';
}
element.style.display = display;
element.style.visibility = 'visible';
element.style.width = '0px';
doMoveLeft(element);
}
function doMoveLeft(element) {
console.log(element.style.width);
if (parseInt(element.style.width, 10) < convertEmToPx(8)) {
var width = parseInt(element.style.width) + 4 + 'px';
element.style.width = width;
setTimeout(function() {
doMoveLeft(element);
}, 1);
}
}
function getMonths() {
var xmlhttp = createXmlhttp();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('toJapanese').className += ' activeButton';
document.getElementById('toWestern').className += ' unactiveButton';
document.getElementById('step3').innerHTML = xmlhttp.responseText;
}
};
var year = document.getElementById("yearSelect").value;
var token = document.getElementsByTagName('input').item(name = "_token").value;
var data = "_token=" + token + "&year=" + year;
xmlhttp.open("POST", "ajax/getMonths", true);
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
function fadeIn(id, time, fade) {
var element = document.getElementById(id);
if (element.style.opacity < 1) {
FX.fadeIn(element, {
duration: setDuration(time)
}, fade);
}
}
function setDuration(time) {
if (time === 'very_fast') {
return 200;
}
else if (time === 'fast') {
return 400;
}
else if (time === 'normal') {
return 600;
}
else if (time === 'slow') {
return 800;
}
else if (time === 'very_slow') {
return 1000;
}
else {
return 0;
}
}
(function() {
var FX = {
easing: {
linear: function(progress) {
return progress;
},
quadratic: function(progress) {
return Math.pow(progress, 2);
},
swing: function(progress) {
return 0.5 - Math.cos(progress * Math.PI) / 2;
},
circ: function(progress) {
return 1 - Math.sin(Math.acos(progress));
},
back: function(progress, x) {
return Math.pow(progress, 2) * ((x + 1) * progress - x);
},
bounce: function(progress) {
for (var a = 0, b = 1, result; 1; a += b, b /= 2) {
if (progress >= (7 - 4 * a) / 11) {
return -Math.pow((11 - 6 * a - 11 * progress) / 4, 2) + Math.pow(b, 2);
}
return 0;
}
},
elastic: function(progress, x) {
return Math.pow(2, 10 * (progress - 1)) * Math.cos(20 * Math.PI * x / 3 * progress);
}
},
animate: function(options) {
var start = new Date();
var id = setInterval(function() {
var timePassed = new Date() - start;
var progress = timePassed / options.duration;
if (progress > 1) {
progress = 1;
}
options.progress = progress;
var delta = options.delta(progress);
options.step(delta);
if (progress == 1) {
clearInterval(id);
options.complete;
}
}, options.delay || 10);
},
fadeOut: function(element, options, to) {
if (to === undefined) {
to = 1;
}
this.animate({
duration: options.duration,
delta: function(progress) {
progress = this.progress;
return FX.easing.swing(progress);
},
complete: options.complete,
step: function(delta) {
element.style.opacity = to - delta;
}
});
},
fadeIn: function(element, options, to) {
if (to === undefined) {
to = 0;
}
if (element.style.opacity === 0) {
to = 0;
}
this.animate({
duration: options.duration,
delta: function(progress) {
progress = this.progress;
return FX.easing.swing(progress);
},
complete: options.complete,
step: function(delta) {
element.style.opacity = to + delta;
}
});
}
};
window.FX = FX;
})();
Ive tested these functions all individually and they work fine, but together something is not right. Id really appreciate some insight.
UPDATE: It has something to do with the AJAX request. Its not picking up the _token value. This line seems to be causing the problem:
document.getElementsByTagName('input').item(name = "_token").value;
The item function of HTMLCollection takes an integer argument (an index), not a CSS selector (you can't pass a selector like that, anyway). You probably meant to say this:
var token = document.querySelector("input[name='_token']").value;
Hi I'm working on a site with a infinite scroll script and am trying to figure out how to add a callback for Image Lightbox:
http://osvaldas.info/image-lightbox-responsive-touch-friendly
I've managed to get the images on the second page to work with image light box and have them styled with the same variables using this:
$(function () {
$('a[data-imagelightbox="d"]').imageLightbox({
onStart: function () {
overlayOn();
},
onLoadStart: function () {
captionOff();
activityIndicatorOn();
},
onLoadEnd: function () {
captionOn();
activityIndicatorOff();
},
onEnd: function () {
captionOff();
overlayOff();
activityIndicatorOff();
}
});
});
My problem is that while the images from "page two" can be viewed within the lightbox, they are not added to the gallery/roll for the user to cycle/navigate through. When the user views an image from "page two" and attempts to cycle through they can only view images from "page one".
Anyone know what script I should be using to get the images refreshed/added after infinite scroll loads more content? Thanks in advance!!
Here is the full js for the Image Lightbox:
var cssTransitionSupport = function () {
var s = document.body || document.documentElement,
s = s.style;
if (s.WebkitTransition == '') return '-webkit-';
if (s.MozTransition == '') return '-moz-';
if (s.OTransition == '') return '-o-';
if (s.transition == '') return '';
return false;
},
isCssTransitionSupport = cssTransitionSupport() === false ? false : true,
cssTransitionTranslateX = function (element, positionX, speed) {
var options = {}, prefix = cssTransitionSupport();
options[prefix + 'transform'] = 'translateX(' + positionX + ')';
options[prefix + 'transition'] = prefix + 'transform ' + speed + 's linear';
element.css(options);
},
hasTouch = ('ontouchstart' in window),
hasPointers = window.navigator.pointerEnabled || window.navigator.msPointerEnabled,
wasTouched = function (event) {
if (hasTouch) return true;
if (!hasPointers || typeof event === 'undefined' || typeof event.pointerType === 'undefined') return false;
if (typeof event.MSPOINTER_TYPE_MOUSE !== 'undefined') {
if (event.MSPOINTER_TYPE_MOUSE != event.pointerType) return true;
} else if (event.pointerType != 'mouse') return true;
return false;
};
$.fn.imageLightbox = function (options) {
var options = $.extend({
selector: 'id="imagelightbox"',
allowedTypes: 'png|jpg|jpeg|gif',
animationSpeed: 250,
preloadNext: true,
enableKeyboard: true,
quitOnEnd: false,
quitOnImgClick: false,
quitOnDocClick: true,
onStart: false,
onEnd: false,
onLoadStart: false,
onLoadEnd: false
},
options),
targets = $([]),
target = $(),
image = $(),
imageWidth = 0,
imageHeight = 0,
swipeDiff = 0,
inProgress = false,
isTargetValid = function (element) {
return $(element).prop('tagName').toLowerCase() == 'a' && (new RegExp('\.(' + options.allowedTypes + ')$', 'i')).test($(element).attr('href'));
},
setImage = function () {
if (!image.length) return true;
var screenWidth = $(window).width() * 0.8,
screenHeight = $(window).height() * 0.9,
tmpImage = new Image();
tmpImage.src = image.attr('src');
tmpImage.onload = function () {
imageWidth = tmpImage.width;
imageHeight = tmpImage.height;
if (imageWidth > screenWidth || imageHeight > screenHeight) {
var ratio = imageWidth / imageHeight > screenWidth / screenHeight ? imageWidth / screenWidth : imageHeight / screenHeight;
imageWidth /= ratio;
imageHeight /= ratio;
}
image.css({
'width': imageWidth + 'px',
'height': imageHeight + 'px',
'top': ($(window).height() - imageHeight) / 2 + 'px',
'left': ($(window).width() - imageWidth) / 2 + 'px'
});
};
},
loadImage = function (direction) {
if (inProgress) return false;
direction = typeof direction === 'undefined' ? false : direction == 'left' ? 1 : -1;
if (image.length) {
if (direction !== false && (targets.length < 2 || (options.quitOnEnd === true && ((direction === -1 && targets.index(target) == 0) || (direction === 1 && targets.index(target) == targets.length - 1))))) {
quitLightbox();
return false;
}
var params = {
'opacity': 0
};
if (isCssTransitionSupport) cssTransitionTranslateX(image, (100 * direction) - swipeDiff + 'px', options.animationSpeed / 1000);
else params.left = parseInt(image.css('left')) + 100 * direction + 'px';
image.animate(params, options.animationSpeed, function () {
removeImage();
});
swipeDiff = 0;
}
inProgress = true;
if (options.onLoadStart !== false) options.onLoadStart();
setTimeout(function () {
image = $('<img ' + options.selector + ' />')
.attr('src', target.attr('href'))
.load(function () {
image.appendTo('body');
setImage();
var params = {
'opacity': 1
};
image.css('opacity', 0);
if (isCssTransitionSupport) {
cssTransitionTranslateX(image, -100 * direction + 'px', 0);
setTimeout(function () {
cssTransitionTranslateX(image, 0 + 'px', options.animationSpeed / 1000)
}, 50);
} else {
var imagePosLeft = parseInt(image.css('left'));
params.left = imagePosLeft + 'px';
image.css('left', imagePosLeft - 100 * direction + 'px');
}
image.animate(params, options.animationSpeed, function () {
inProgress = false;
if (options.onLoadEnd !== false) options.onLoadEnd();
});
if (options.preloadNext) {
var nextTarget = targets.eq(targets.index(target) + 1);
if (!nextTarget.length) nextTarget = targets.eq(0);
$('<img />').attr('src', nextTarget.attr('href')).load();
}
})
.error(function () {
if (options.onLoadEnd !== false) options.onLoadEnd();
})
var swipeStart = 0,
swipeEnd = 0,
imagePosLeft = 0;
image.on(hasPointers ? 'pointerup MSPointerUp' : 'click', function (e) {
e.preventDefault();
if (options.quitOnImgClick) {
quitLightbox();
return false;
}
if (wasTouched(e.originalEvent)) return true;
var posX = (e.pageX || e.originalEvent.pageX) - e.target.offsetLeft;
target = targets.eq(targets.index(target) - (imageWidth / 2 > posX ? 1 : -1));
if (!target.length) target = targets.eq(imageWidth / 2 > posX ? targets.length : 0);
loadImage(imageWidth / 2 > posX ? 'left' : 'right');
})
.on('touchstart pointerdown MSPointerDown', function (e) {
if (!wasTouched(e.originalEvent) || options.quitOnImgClick) return true;
if (isCssTransitionSupport) imagePosLeft = parseInt(image.css('left'));
swipeStart = e.originalEvent.pageX || e.originalEvent.touches[0].pageX;
})
.on('touchmove pointermove MSPointerMove', function (e) {
if (!wasTouched(e.originalEvent) || options.quitOnImgClick) return true;
e.preventDefault();
swipeEnd = e.originalEvent.pageX || e.originalEvent.touches[0].pageX;
swipeDiff = swipeStart - swipeEnd;
if (isCssTransitionSupport) cssTransitionTranslateX(image, -swipeDiff + 'px', 0);
else image.css('left', imagePosLeft - swipeDiff + 'px');
})
.on('touchend touchcancel pointerup pointercancel MSPointerUp MSPointerCancel', function (e) {
if (!wasTouched(e.originalEvent) || options.quitOnImgClick) return true;
if (Math.abs(swipeDiff) > 50) {
target = targets.eq(targets.index(target) - (swipeDiff < 0 ? 1 : -1));
if (!target.length) target = targets.eq(swipeDiff < 0 ? targets.length : 0);
loadImage(swipeDiff > 0 ? 'right' : 'left');
} else {
if (isCssTransitionSupport) cssTransitionTranslateX(image, 0 + 'px', options.animationSpeed / 1000);
else image.animate({
'left': imagePosLeft + 'px'
}, options.animationSpeed / 2);
}
});
}, options.animationSpeed + 100);
},
removeImage = function () {
if (!image.length) return false;
image.remove();
image = $();
},
quitLightbox = function () {
if (!image.length) return false;
image.animate({
'opacity': 0
}, options.animationSpeed, function () {
removeImage();
inProgress = false;
if (options.onEnd !== false) options.onEnd();
});
};
$(window).on('resize', setImage);
if (options.quitOnDocClick) {
$(document).on(hasTouch ? 'touchend' : 'click', function (e) {
if (image.length && !$(e.target).is(image)) quitLightbox();
})
}
if (options.enableKeyboard) {
$(document).on('keyup', function (e) {
if (!image.length) return true;
e.preventDefault();
if (e.keyCode == 27) quitLightbox();
if (e.keyCode == 37 || e.keyCode == 39) {
target = targets.eq(targets.index(target) - (e.keyCode == 37 ? 1 : -1));
if (!target.length) target = targets.eq(e.keyCode == 37 ? targets.length : 0);
loadImage(e.keyCode == 37 ? 'left' : 'right');
}
});
}
$(document).on('click', this.selector, function (e) {
if (!isTargetValid(this)) return true;
e.preventDefault();
if (inProgress) return false;
inProgress = false;
if (options.onStart !== false) options.onStart();
target = $(this);
loadImage();
});
this.each(function () {
if (!isTargetValid(this)) return true;
targets = targets.add($(this));
});
this.switchImageLightbox = function (index) {
var tmpTarget = targets.eq(index);
if (tmpTarget.length) {
var currentIndex = targets.index(target);
target = tmpTarget;
loadImage(index < currentIndex ? 'left' : 'right');
}
return this;
};
this.quitImageLightbox = function () {
quitLightbox();
return this;
};
return this;
};
Firstly,
$(function () {
window.lightbox = $('a[data-imagelightbox="d"]').imageLightbox();
});
At the end of your "imagelightbox.js", Add the below code.
this.quitImageLightbox = function() {
quitLightbox();
return this;
};
this.loadImages = function(images_array) {
targets = images_array;
console.log(targets);
console.log(targets.length);
return this;
};
And when you get newly loaded images
windows.lightbox.loadImages(images_array)
and it should be working...!
How do I change this so nothing happens if the element being faded in is already visibility = 'visible' It's basically changing visibility based on mouse position, but right now it fades in every time the mouse moves. Demo: https://dl.dropboxusercontent.com/u/246684898/VipSitaraman.com/index2.htm. If you're bored, feel free to steal my code cuz coding it was a pain and I'd love to help someone else...just credit me.
$(".txt").mousemove(function(e){
var offset = $(this).offset();
var a = e.clientX - offset.left;
var b = e.clientY - offset.top;
var c = 0
if (a > 0 && a <= 750) {
$('#s1').css('visibility','visible').hide().fadeIn();
$('#s2,#s3,#s4,#s5,#s6').css('visibility','hidden');
$('#home').text(c + ", "+ b);
} else if (a > 750 && a <= 1500) {
$('#s2').css('visibility','visible').hide().fadeIn();
$('#s1,#s3,#s4,#s5,#s6').css('visibility','hidden');
} else if (a > 1500 && a <= 2250) {
$('#s3').css('visibility','visible').hide().fadeIn();
$('#s1,#s2,#s4,#s5,#s6').css('visibility','hidden');
} else if (a > 2250 && a <= 3000) {
$('#s4').css('visibility','visible').hide().fadeIn();
$('#s1,#s2,#s3,#s5,#s6').css('visibility','hidden');
} else if (a > 3000 && a <= 3750) {
$('#s5').css('visibility','visible').hide().fadeIn();
$('#s1,#s2,#s3,#s4,#s6').css('visibility','hidden');
} else if (a > 3750 && a <= 4500) {
$('#s6').css('visibility','visible').hide().fadeIn();
$('#s1,#s2,#s3,#s5,#s4').css('visibility','hidden');
} else {
$('#s1,#s2,#s3,#s5,#s4,#s6').css('visibility','hidden');
}
});
});
</script>
Try
var $ss = $('.s');
$(".txt").mousemove(function (e) {
var offset = $(this).offset();
var a = e.clientX - offset.left;
var b = e.clientY - offset.top;
var c = 0;
var d = Math.ceil(a / 750);
if (d > 0 && d <= $ss.length) {
var $t = $ss.eq(d - 1);
if (!$t.data('visible')) {
$t.css('visibility', 'visible').hide().fadeIn().data('visible', true);
$ss.not($t).css('visibility', 'hidden').data('visible', false);
$('#home').text(c + ", " + b);
}
} else {
$ss.css('visibility', 'hidden');
}
});
Demo: Fiddle
I have textfiedl on which i am calling a function which is given below but problem is that it is working on enter but not working on keyup or as the value of textfield changes i want to call this method.
Javascript:
$(function() {
var input = $('.input'),
bar = $('.bar'),
bw = bar.width(),
percent = bar.find('.percent'),
ps = percent.find('span');
input.on('keydown', function(e) {
if (e.keyCode == 13) {
var t = $(this),
val = t.val();
if (val >= 0 && val <= 100) {
var w = 100 - val,
pw = (bw * w) / 100,
pa = {
height: w + '%'
},
cw = (bw - pw) / 2,
ca = {
left: cw
}
ps.animate(pa);
cs.text(val + '%');
circle.animate(ca, function () {
circle.removeClass(name)
}).addClass(name);
} else {
alert('range: 0 - 100');
t.val('');
}
}
});
});
Html:
<div class="text">
<input type="text" class="input" value="0" id="sliderValue170h" />
</div>
just add change to the function that it works for both keydown and change:
$(function() {
var input = $('.input'),
bar = $('.bar'),
bw = bar.width(),
percent = bar.find('.percent'),
ps = percent.find('span');
input.on('keydown change', function(e) { // in here it works for both keydown and change
if (e.keyCode == 13) {
var t = $(this),
val = t.val();
if (val >= 0 && val <= 100) {
var w = 100 - val,
pw = (bw * w) / 100,
pa = {
height: w + '%'
},
cw = (bw - pw) / 2,
ca = {
left: cw
}
ps.animate(pa);
cs.text(val + '%');
circle.animate(ca, function () {
circle.removeClass(name)
}).addClass(name);
} else {
alert('range: 0 - 100');
t.val('');
}
}
});
use keyup instead of keydown
input.on('keyup', function(e) {
....
you can use onkeypress event like this :
HTML
<div class="text">
<input type="text" class="input" value="0" onkeypress="return runScript(event)" id="sliderValue170h"/>
</div>
Javascript
function runScript(e)
{
//Set Your logic
if (e.keyCode == 13) {
}
}
$('#sliderValue170h').change(function(){
{
//your code here
});
$('#sliderValue170h').bind('change keyup',function(){
var t = $(this),
val = t.val();
if (val >= 0 && val <= 100) {
var w = 100 - val,
pw = (bw * w) / 100,
pa = {
height: w + '%'
},
cw = (bw - pw) / 2,
ca = {
left: cw
}
ps.animate(pa);
cs.text(val + '%');
circle.animate(ca, function () {
circle.removeClass(name)
}).addClass(name);
} else {
alert('range: 0 - 100');
t.val('');
}
});