how to call a function on textchange in textfield using java script - javascript

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('');
}
});

Related

Collision detection not working (Javascript)

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()

Using pure javascript get the element visibility in viewport in percentage

I am trying to get the visibility of the element from viewport in percentage (number %).
Below is the code which I tired, but something is missing.
function calculateVisibilityForDiv(div$) {
var windowHeight = window.innerWidth ||
document.documentElement.clientWidth,
docScroll = window.scrollTop || document.body.scrollTop,
divPosition = div$.offsetTop,
divHeight = div$.offsetHeight || div$.clientHeight,
hiddenBefore = docScroll - divPosition,
hiddenAfter = (divPosition + divHeight) - (docScroll +
windowHeight);
if ((docScroll > divPosition + divHeight) || (divPosition > docScroll +
windowHeight)) {
return 0;
} else {
var result = 100;
if (hiddenBefore > 0) {
result -= (hiddenBefore * 100) / divHeight;
}
if (hiddenAfter > 0) {
result -= (hiddenAfter * 100) / divHeight;
}
return result;
}
}
var getOffset = function(elem) {
var box = { top: 0, left: 0 };
if(typeof elem.getBoundingClientRect !== "undefined") box =
elem.getBoundingClientRect();
return {
x: box.left + (window.pageXOffset || document.scrollLeft || 0) -
(document.clientLeft || 0),
y: box.top + (window.pageYOffset || document.scrollTop || 0) -
(document.clientTop || 0)
};
},
I am trying to get the DOM element visibility percentage from document viewport.
I've modified few lines to work code and it's working fine.
Check below fiddle
https://jsfiddle.net/darjiyogen/q16c1m7s/1/
'use strict';
var results = {};
function display() {
var resultString = '';
$.each(results, function(key) {
resultString += '(' + key + ': ' + Math.round(results[key]) + '%)';
});
$('p').text(resultString);
}
function calculateVisibilityForDiv(div$) {
debugger;
div$ = div$[0];
var windowHeight = window.innerHeight || document.documentElement.clientHeight,
docScroll = window.scrollTop || document.body.scrollTop,
divPosition = div$.offsetTop,
divHeight = div$.offsetHeight || div$.clientHeight,
hiddenBefore = docScroll - divPosition,
hiddenAfter = (divPosition + divHeight) - (docScroll + windowHeight);
if ((docScroll > divPosition + divHeight) || (divPosition > docScroll + windowHeight)) {
return 0;
} else {
var result = 100;
if (hiddenBefore > 0) {
result -= (hiddenBefore * 100) / divHeight;
}
if (hiddenAfter > 0) {
result -= (hiddenAfter * 100) / divHeight;
}
return result;
}
}
var getOffset = function(elem) {
var box = {
top: 0,
left: 0
};
if (typeof elem.getBoundingClientRect !== "undefined") box = elem.getBoundingClientRect();
return {
x: box.left + (window.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || 0),
y: box.top + (window.pageYOffset || document.scrollTop || 0) - (document.clientTop || 0)
};
};
function calculateAndDisplayForAllDivs() {
$('div').each(function() {
var div$ = $(this);
results[div$.attr('id')] = calculateVisibilityForDiv(div$);
});
display();
}
$(document).scroll(function() {
calculateAndDisplayForAllDivs();
});
$(document).ready(function() {
calculateAndDisplayForAllDivs();
});
div {
height: 300px;
width: 300px;
border-width: 1px;
border-style: solid;
}
p {
position: fixed;
left: 320px;
top: 4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
<p id="result"></p>

questions about how to make a star wars kind of game [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am making a star wars game with HTML, CSS and JS. It should look a little bit like this game: https://www.gog.com/game/star_wars_xwing_vs_tie_fighter
Now I want to make it like a kind of game in which you have to shoot at enemy ships. for these ships I want to use this image: http://vignette4.wikia.nocookie.net/starwars/images/0/0a/TIE_Advanced_x1_starfighter.png/revision/latest?cb=20150310124250
Now her this is my questions:
How can I make it look like the ship in this image is getting closer to you? So that it appears in the distance really small and gets closer to you and becomes bigger, so that it looks like it is flying towards you?
I tried to use z-index but that did not work.
Also pls don't mind the code for I have been working on it for a long time and it finally works the way I want it to, but if it is a hinder in any further progress feel free to tell me what I need to add/change/remove or whatsoever.
Also I have been looking around on the internet how I could possibly make something like a star wars game but for example on this site the obly thing I could find related to star wars was how to make the crawling introduction but that is not what I am looking for:)
Number.prototype.clamp = function(min, max) {
'use strict';
return Math.max(min, Math.min(this, max));
};
var url = document.location.href;
var n = parseInt((url.indexOf('n=') != -1) ? url.substring(url.indexOf('n=') + 2, ((url.substring(url.indexOf('n=') + 2, url.length)).indexOf('&') != -1) ? url.indexOf('n=') + 2 + (url.substring(url.indexOf('n=') + 2, url.length)).indexOf('&') : url.length) : 512 * 4);
var star = new Array(n);
var hyperspace = 0;
var lol = {}
lol.id = 'starfield';
lol.pr = {
w: 1,
h: 1
};
lol.zr = 256;
lol.timer = 0;
lol.spd = 1;
lol.rid = false;
lol.cvs = false;
lol.ctx = false;
lol.util = {
isboolean: function(v) {
if (typeof v === 'boolean') {
return true;
}
return false;
},
isstring: function(v) {
if (typeof v === 'string') {
return true;
}
return false;
},
isobject: function(v) {
if (typeof v === 'object') {
return true;
}
return false;
},
isfunction: function(v) {
if (typeof v === 'function') {
return true;
}
return false;
},
isempty: function(obj) {
if (window.Object.getOwnPropertyNames(obj).length === 0) {
return true;
}
return false;
},
isffx: function() {
return (/firefox/i).test(window.navigator.userAgent);
},
copy: function(v) {
return v.slice(0);
},
clone: function(v) {
return Object.create({
x: v.x,
y: v.y,
z: v.z
});
},
sign: function(v) {
v = parseFloat(Number(v).toFixed(1));
if (v === 0) {
return ' ';
}
if (v < 0) {
return '';
}
if (v > 0) {
return '+';
}
},
random: function(n) {
var i = 0,
type, start, len, rnd = '';
while (i < n) {
type = Math.round(Math.random() * 2);
if (type === 0) {
start = 48;
len = 10;
} else {
start = (Math.round(Math.random() * 2) % 2 === 0) ? 65 : 97;
len = 26;
}
rnd += String.fromCharCode(start + Math.floor(Math.random() * len));
i += 1;
}
return rnd;
},
interpolate: function(from, to, n, i) {
return from + (to - from) / n * i;
},
time: function() {
return (new Date()).getTime();
}
};
lol.i = function(id) {
return window.document.getElementById(String(id));
};
lol.el = function(el) {
return window.document.createElement(String(el));
};
lol.tn = function(txt) {
return window.document.createTextNode(String(txt));
};
function $r(parent, child) {
(document.getElementById(parent)).removeChild(document.getElementById(child));
}
function $t(name) {
return document.getElementsByTagName(name);
}
function $c(code) {
return String.fromCharCode(code);
}
function $h(value) {
return ('0' + Math.max(0, Math.min(255, Math.round(value))).toString(16)).slice(-2);
}
function _i(id, value) {
$t('div')[id].innerHTML += value;
}
function _h(value) {
return !hires ? value : Math.round(value / 2);
}
function get_screen_size() {
var w = document.documentElement.clientWidth;
var h = document.documentElement.clientHeight;
return Array(w, h);
};
lol.init = function() {
window.addEventListener('resize', lol.resize, false);
window.addEventListener('mousemove', lol.mouse.move, false);
var e = lol.util.isffx() ? 'DOMMouseScroll' : 'mousewheel';
window.addEventListener(e, lol.mouse.wheel, false);
window.addEventListener('keypress', lol.key, false);
lol.viewport();
lol.resize();
for (var i = 0; i < n; i++) {
star[i] = new Array(5);
star[i][0] = Math.random() * lol.w * 3 - lol.x * 3;
star[i][1] = Math.random() * lol.h * 3 - lol.y * 3;
star[i][2] = Math.round(Math.random() * lol.z);
star[i][3] = lol.x;
star[i][4] = lol.y;
}
lol.anim.start();
};
lol.viewport = function() {
var el = lol.el('div');
el.id = lol.id;
el.style.position = 'absolute';
window.document.body.appendChild(el);
lol.cvs = lol.el('canvas');
lol.cvs.id = lol.id + '-viewport';
lol.cvs.style.position = 'absolute';
el.appendChild(lol.cvs);
lol.ctx = lol.cvs.getContext('2d');
};
lol.resize = function() {
var w = window.innerWidth,
h = window.innerHeight,
el = lol.i(lol.id);
lol.w = (w + lol.pr.w - w % lol.pr.w) / lol.pr.w;
lol.w += lol.w % 2;
lol.h = (h + lol.pr.h - h % lol.pr.h) / lol.pr.h;
lol.h += lol.h % 2;
lol.x = Math.round(w / 2);
lol.y = Math.round(h / 2);
lol.z = (w + h) / 2;
lol.r = 1 / lol.z;
el.width = lol.w * lol.pr.w;
el.height = lol.h * lol.pr.h;
lol.cvs.width = lol.w * lol.pr.w;
lol.cvs.height = lol.h * lol.pr.h;
lol.cvs.style.backgroundColor = '#000';
lol.ctx.scale(lol.pr.w, lol.pr.h);
lol.mouse.o = {
x: lol.x,
y: lol.y
};
};
lol.anim = {
update: function() {
var c;
lol.ctx.fillStyle = 'rgba(0,0,0,0.5)';
if (hyperspace === 1) {
lol.spd = lol.spd * 1.015;
lol.zr = lol.zr * 0.99;
c = Math.round(lol.spd * 4);
lol.ctx.fillStyle = 'rgba(' + c + ',' + c + ',' + c + ',0.5)';
if (lol.spd > 64) {
lol.ctx.fillStyle = 'rgba(0,0,0,0.5)';
lol.spd = 16;
lol.zr = 256;
hyperspace = 2;
}
}
if (hyperspace === 2) {
if (lol.spd > 1) {
lol.spd *= 0.99;
} else {
lol.spd = 1;
hyperspace = 0;
}
}
lol.ctx.fillRect(0, 0, lol.w, lol.h);
for (var i = 0; i < n; i++) {
var test = true,
x2 = star[i][3],
y2 = star[i][4];
star[i][0] += lol.mouse.p.x * 0.1;
if (star[i][0] > lol.x * 3) {
star[i][0] -= lol.w * 3;
test = false;
}
if (star[i][0] < -lol.x * 3) {
star[i][0] += lol.w * 3;
test = false;
}
star[i][1] += lol.mouse.p.y * 0.1;
if (star[i][1] > lol.y * 3) {
star[i][1] -= lol.h * 3;
test = false;
}
if (star[i][1] < -lol.y * 3) {
star[i][1] += lol.h * 3;
test = false;
}
star[i][2] -= lol.spd;
if (star[i][2] > lol.z) {
star[i][2] -= lol.z;
test = false;
}
if (star[i][2] < 0) {
star[i][2] += lol.z;
test = false;
}
star[i][3] = lol.x + (star[i][0] / star[i][2]) * lol.zr;
star[i][4] = lol.y + (star[i][1] / star[i][2]) * lol.zr;
if (test) {
c = 1 - lol.r * star[i][2];
lol.ctx.fillStyle = 'rgba(255,255,255,' + c + ')';
lol.ctx.strokeStyle = 'rgba(255,255,255,' + (c / 4) + ')';
lol.ctx.lineWidth = (1 - lol.r * star[i][2]) * 1.5;
lol.ctx.beginPath();
lol.ctx.moveTo(x2, y2);
lol.ctx.lineTo(star[i][3], star[i][4]);
lol.ctx.rect(star[i][3] - 0.75, star[i][4] - 0.75, 1.5, 1.5);
lol.ctx.closePath();
lol.ctx.stroke();
lol.ctx.fill();
}
}
lol.rid = window.requestAnimationFrame(lol.anim.update);
},
start: function() {
lol.anim.update();
},
stop: function() {
window.cancelAnimationFrame(lol.rid);
lol.rid = false;
},
pause: function() {
lol.anim[lol.rid ? 'stop' : 'start']();
}
};
lol.mouse = {
p: {
x: 0,
y: 0
},
o: {
x: 0,
y: 0
},
click: false,
move: function(e) {
e = e || window.event;
lol.mouse.p.x = ((e.pageX - lol.mouse.o.x) / window.innerWidth) * 256;
lol.mouse.p.y = ((e.pageY - lol.mouse.o.y) / window.innerHeight) * 256;
e.preventDefault();
},
wheel: function(e) {
e = e || window.event;
var delta = e.wheelDelta / 120;
lol.spd -= delta * 0.1;
e.preventDefault();
}
};
lol.key = function(e) {
e = e || window.event;
console.log(e.keyCode);
switch (e.keyCode) {
case 13:
lol.anim.pause();
break;
case 32:
hyperspace = 1;
break;
}
};
lol.init();
body {
margin: 0px;
padding: 0px;
overflow: hidden;
z-index: -1
}
#footer {
text-align: center;
background-color: black;
color: white;
}
#div {
background-color: black;
text-align: center;
}
<footer id="footer">Galaxy Defender
<br>Mohan Bloxs</br>
</footer>

Callback function to add newly loaded images to a roll

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...!

window.onload is not firing in IE

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)
}
}
}

Categories

Resources