I'm trying to spawn randomly generated targets on the screen using a function to copy an invisible image of the target to be spawned at a random place within the screen using window object properties.
For this to happen I think the image have to have position set to absolute, but then several images may be spawned in a way that they will overlap, how can I prevent this from happening?
The div element where I copy my first image and also store the other copies.
<div id="targetsDiv">
<img src="target2.png" alt="target_shot" class="target" />
</div>
Inside the script:
var x_pixels = window.innerWidth - 180;
var y_pixels = window.innerHeight - 180;
var x_midScreen = window.innerWidth / 2;
var y_midScreen = window.innerHeight / 2;
var xRandom = Math.floor(Math.random()*x_pixels) +1;
var yRandom = Math.floor(Math.random()*y_pixels) +1;
var targetCollection = document.getElementById("targetsDiv");
var targetCopy = targetCollection.innerHTML
var targetList = document.getElementsByClassName("target");
targetList[0].style.display = "none";
var targetNr = 1;
var numberOfSpawns = 3;
function spawnTargets () {
while (targetNr <= numberOfSpawns) {
if ((xRandom < x_midScreen - 126 || xRandom > x_midScreen + 26) || (yRandom < y_midScreen - 126 || yRandom > y_midScreen + 26)) {
targetCollection.innerHTML += targetCopy;
targetList[targetNr].style.left = xRandom + "px";
targetList[targetNr].style.top = yRandom + "px";
targetNr++;
}
xRandom = Math.floor(Math.random()*x_pixels) +1;
yRandom = Math.floor(Math.random()*y_pixels) +1;
}
}
PS: I appreciate all help, tips and tweaks that you guys provide:) Thanks for helping
The area you want to exclude in the centre of the screen is rather large, and on my little laptop, there isn't even any room to still show the random positioned images.
But anyway, this piece of code should do the job -- I added some infinite loop protection which on my PC was a life-saver:
HTML (added style attribute)
<div id="targetsDiv">
<img src="target2.png" alt="target_shot" class="target"
style="visibility:hidden"/>
</div>
JavaScript:
window.addEventListener('load', function () {
var targetCollection = document.getElementById("targetsDiv");
var template = document.getElementsByClassName("target")[0];
var targetWidth = template.offsetWidth;
var targetHeight = template.offsetHeight;
var x_pixels = window.innerWidth - targetWidth;
var y_pixels = window.innerHeight - targetHeight;
var x_midScreen = window.innerWidth / 2;
var y_midScreen = window.innerHeight / 2;
function spawnTargets (numberOfSpawns) {
var targets = [];
var count = 0; // infinite recursion protection
for (var i = 0; i < numberOfSpawns; i++) {
do {
do {
var x = Math.floor(Math.random()*x_pixels);
var y = Math.floor(Math.random()*y_pixels);
if (count++ > 200) {
console.log('give up');
return;
}
} while ((x >= x_midScreen-450 && x <= x_midScreen+300) && (y >= y_midScreen-350 || y <= y_midScreen+200));
for (var j = 0; j < i; j++) {
if (x >= targets[j].x - targetWidth && x <= targets[j].x + targetWidth &&
y >= targets[j].y - targetHeight && y <= targets[j].y + targetHeight) break; // not ok!
}
} while (j < i);
targets.push({x, y});
img = document.createElement('img');
img.src = template.src;
img.setAttribute('width', targetWidth + 'px');
img.setAttribute('height', targetHeight + 'px');
img.className = template.className;
targetCollection.appendChild(img);
img.style.left = x + "px";
img.style.top = y + "px";
}
}
spawnTargets(3);
});
Related
I have the following problem, you will see I have a web page where I implement the rangeslider plugin on PC it works correctly but on mobile I can't explain myself: when on mobile I select the slider I cannot make it go up or down or change the amount it has, it is only modified while The scroll is used but as you know with the scroll the user moves on mobile, therefore it cannot work so check what I mean on the page
this is the link of the page: http://ucreativa.work/linux/nsite2/product.php
As you can see, it works well on PC, but if they try to use it on mobile, the slider does not work.
What do you think that might be? I append the js code that I use I don't append the css because it is a lot of code that is not relevant
my question is can this plugin work on mobile?
var cpu_cur_val = '2';
var ram_cur_val = '4';
var disk_cur_val = '8';
var backup_cur_val = '30';
var ips_cur_val = '0';
function new_range (wrapper) {
// Variables to use later
var rangeWrapper = document.querySelector('.' + wrapper + '__wrapper');
var rangeInput = document.querySelector('.' + wrapper + '__input');
var rangeValues = document.querySelector('.' + wrapper + '__values');
var rangeValueNumberBottom = document.querySelector('.' + wrapper + '__value__number--bottom');
var rangeValueTextBottom = document.querySelector('.' + wrapper + '__value__text--bottom');
var rangeSliderPaths = document.querySelectorAll('.' + wrapper + '__slider__path');
var mouseX = 0;
var mouseY = 0;
var mouseInitialY = 0;
var mouseDy = 0;
var mouseDyLimit = 25;
var mouseDyFactor = 3;
var max = parseInt(rangeInput.max);
var rangeMin = parseInt(rangeInput.min);
var rangeMax = parseInt(rangeInput.max);
var rangeValue = parseInt(rangeInput.value);
var rangeHeight = 320;
var currentY = rangeHeight * rangeValue / max;
var rangeMinY = rangeHeight * rangeMin / max;
var rangeMaxY = rangeHeight * rangeMax / max;
var scaleMax = 0.32;
var scale, newPath, newY, newSliderY, lastMouseDy, rangeWrapperLeft, pageX, pageY;
// Update slider value, initially using the `input` value
updateValue();
// Function to build the slider `path`, using the given `dy` and `ty` values
function buildPath(dy, ty) {
return 'M 0 ' + ty + ' q ' + mouseX + ' ' + dy + ' 120 0 l 0 320 l -120 0 Z';
}
// Function to update the slider value
function updateValue() {
// Clear animations if are still running
anime.remove([rangeValues, rangeSliderPaths[0], rangeSliderPaths[1]]);
// Calc the `input` value using the current `y`
rangeValue = parseInt(currentY * max / rangeHeight);
// Calc `scale` value for numbers
scale = (rangeValue - rangeMin) / (rangeMax - rangeMin) * scaleMax;
// Update `input` value
rangeInput.value = rangeValue;
// rangeSum.innerText = rangeValue;
rangeValueNumberBottom.innerText = rangeValue;
// Match the javascript value to real input value;
rangeInput.setAttribute('value', rangeValue);
switch (wrapper) {
default:
rangeValueNumberBottom.innerText = rangeValue;
break;
case 'cpu':
cpu_cur_val = rangeValue;
break;
case 'ram':
if (rangeValueNumberBottom.innerText == '0') {
rangeValueTextBottom.innerText = 'זיכרון (MB)';
rangeValueNumberBottom.innerText = '500';
} else {
rangeValueTextBottom.innerText = 'זיכרון (GB)';
}
ram_cur_val = rangeValue;
break;
case 'disk':
rangeValueNumberBottom.innerText = rangeValue + '0';
disk_cur_val = rangeValue;
break;
case 'backup':
if (rangeValueNumberBottom.innerText == '0') {
rangeValueNumberBottom.innerText = '0';
} else {
rangeValueNumberBottom.innerText = rangeValue + '0';
}
backup_cur_val = rangeValue;
break;
case 'ips':
ips_cur_val = rangeValue;
break;
}
// Some maths calc
if (Math.abs(mouseDy) < mouseDyLimit) {
lastMouseDy = mouseDy;
} else {
lastMouseDy = mouseDy < 0 ? -mouseDyLimit : mouseDyLimit;
}
// Calc the `newSliderY` value to build the slider `path`
newSliderY = currentY + lastMouseDy / mouseDyFactor;
if (newSliderY < rangeMinY || newSliderY > rangeMaxY) {
newSliderY = newSliderY < rangeMinY ? rangeMinY : rangeMaxY;
}
// Build `path` string and update `path` elements
newPath = buildPath(lastMouseDy, rangeHeight - newSliderY);
rangeSliderPaths[0].setAttribute('d', newPath);
rangeSliderPaths[1].setAttribute('d', newPath);
}
// Function to simulate the elastic behavior
function elasticRelease() {
// Morph the paths to the opposite direction, to simulate a strong elasticity
anime({
targets: rangeSliderPaths,
d: buildPath(-lastMouseDy * 1.3, rangeHeight - (currentY - lastMouseDy / mouseDyFactor)),
duration: 150,
easing: 'linear',
complete: function () {
// Morph the paths to the normal state, using the `elasticOut` easing function (default)
anime({
targets: rangeSliderPaths,
d: buildPath(0, rangeHeight - currentY),
duration: 4000,
elasticity: 880
});
}
});
}
// Handle `mousedown` and `touchstart` events, saving data about mouse position
function mouseDown(e) {
mouseY = mouseInitialY = e.targetTouches ? e.targetTouches[0].pageY : e.pageY;
rangeWrapperLeft = rangeWrapper.getBoundingClientRect().left;
}
// Handle `mousemove` and `touchmove` events, calculating values to morph the slider `path` and translate values properly
function mouseMove(e) {
if (mouseY) {
pageX = e.targetTouches ? e.targetTouches[0].pageX : e.pageX;
pageY = e.targetTouches ? e.targetTouches[0].pageY : e.pageY;
mouseX = pageX - rangeWrapperLeft;
mouseDy = (pageY - mouseInitialY) * mouseDyFactor;
newY = currentY + mouseY - pageY;
// alert(newY);
if (newY >= rangeMinY && newY <= rangeMaxY) {
currentY = newY;
mouseY = pageY;
} else {
currentY = newY < rangeMinY ? rangeMinY : rangeMaxY;
}
// After doing maths, update the value
updateValue();
}
}
// Handle `mouseup`, `mouseleave` and `touchend` events
function mouseUp() {
// Trigger elastic animation in case `y` value has changed
if (mouseDy) {
elasticRelease();
}
// Reset values
mouseY = mouseDy = 0;
}
// Events listeners
rangeWrapper.addEventListener('mousedown', mouseDown);
rangeWrapper.addEventListener('touchstart', mouseDown);
rangeWrapper.addEventListener('mousemove', mouseMove);
rangeWrapper.addEventListener('touchmove', mouseMove);
rangeWrapper.addEventListener('mouseup', mouseUp);
rangeWrapper.addEventListener('mouseleave', mouseUp);
rangeWrapper.addEventListener('touchend', mouseUp);
}
I'm trying to create snap to top divs that cover the entire page and I have it working, it's just that after they snap to the top they don't unsnap and stay fixed to the top. I'm using the answer given by mu is too short from this previous question scroll then snap to top but I can't get it to unsnap.
Here's a jsbin of the code.
var h = 0;
var notif;
var notif2;
var init;
var docked = false;
function getSize() {
h = window.innerHeight;
notif = document.getElementById("notif");
notif2 = document.getElementById("notif2");
var fl = document.getElementById("floater");
init = notif.scrollTop;
notif.style.top = "" + h + "px";
var h2 = h / 2;
fl.style.marginTop = "" + h2 + "px";
notif.style.height = "" + h + "px";
var twoh = 3 * h2;
notif2.style.top = "" + h + "px";
notif2.style.height = "" + h + "px";
}
window.onscroll = function() {
if (!docked && (notif.offsetTop - document.body.scrollTop < 0)) {
console.log("in loop");
notif.style.top = 0;
notif.style.position = 'fixed';
notif2.style.marginTop = "" + h + "px";
docked = true;
} else if (docked && document.body.scrollTop <= init) {
notif.style.position = 'block';
while (notif.style.top <= h) {
var ab = Math.abs(notif.offsetTop)
var ab2 = Math.abs(document.body.scrollTop);
notif.style.top = init + 'px';
}
if (notif.style.top == h || notif.style.top == h - 1) {
docked = false;
}
}
};
<body onload="getSize()">
<div class="contain">
<div id="floater">
<h1 class="white">Hello, World</h1>
Link 1 Link 2
</div>
</div>
<div class="announcements" id="notif">
Please cover the previous text on the page. If this works i will be really excited.
</div>
<div class="announcements2" id="notif2">
Cover the white page.
</div>
</body>
Save the values used before you set these, and reset them when you "un-dock". Simply setting "docked" to show that you're un-docked is not enough.
This code is an example of how to do that from your staring point.
Here's how I saved it and got something like the behaviour you mention
var h = 0;
var notif;
var notif2;
var init;
var docked = false;
// holding space for reset values
var holdNotifyStyleTop;
var holdNotifyOffsetTop;
var holdNotif2StyleMarginTop;
function getSize() {
h = window.innerHeight;
notif = document.getElementById("notif");
notif2 = document.getElementById("notif2");
var fl = document.getElementById("floater");
init = notif.offsetTop;
notif.style.top = ""+h+"px";
var h2 = h/2;
fl.style.marginTop = ""+h2+"px";
notif.style.height = ""+h+"px";
var twoh = 3*h2;
notif2.style.top=""+h+"px";
notif2.style.height = ""+h+"px";
}
window.onscroll = function () {
if (!docked && (notif.offsetTop - document.body.scrollTop < 0)) {
console.log("--- DOCKING ---");
// save current values
holdNotifyStyleTop = notif.style.top;
holdNotifyOffsetTop = notif.offsetTop;
holdNotif2StyleMarginTop = notif2.style.marginTop;
notif.style.top = 0;
notif.style.position = 'fixed';
notif2.style.marginTop=""+h+"px";
docked = true;
} else if (docked && document.body.scrollTop <= init) {
console.log("--- Un-DOCKING ---");
notif.style.top = holdNotifyStyleTop;
notif.style.position = 'relative';
notif2.style.marginTop=holdNotif2StyleMarginTop;
notif.offsetTop = holdNotifyOffsetTop;
docked = false;
}
};
Hello I am having errors with my code:
https://jsfiddle.net/wzhm2whj/
<script>
//Initial Global variables
var mainloop_frame_time = 34;
var top = 0;
var rootMenu = document.getElementById('menu');
var rootMenuDivs = rootMenu.getElementsByTagName('div')[0];
var rootListDivs = rootMenuDivs.getElementsByTagName('ul')[0];
var childDivs = rootListDivs.getElementsByTagName('div');
var childDiv = childDivs[0];
var childDiv_counter = 0;
var child_change_flag = true;
var child_index_increment = 0;
var child_index_amount = childDivs.length;
//var child_animation_keyframe = 0;
var frame = 0;
var childDiv_tmp1_position = 0;
//finding the web browsers viewport size.
var elem = (document.compatMode === "CSS1Compat") ? document.documentElement : document.body;
var client_height = elem.clientHeight;
var process_array = new Array();
//Initial styling
for (var i = 0; i < childDivs.length; i++) {
var childDiv = childDivs[0];
childDiv.style.backgroundColor = "antiquewhite";
}
var childDiv = childDivs[0];
//rotate function variables
var rotate_div;
var rotate_passed_deg;
var rotate_deg_stop;
var rotate_results;
var rotate_current_deg = 0;
var speed_modifier = 1;
var tmp1_speed = 0;
//case flags
case2_flag = -1;
case3_flag = -1;
//This may not be needed >>> If not, put all code in mainloop.
var processes_logic = function() {
switch (frame) {
case 0:
process_array.push(menu_child0);
break;
//this case is when the previous case is 80% done
case 28:
rootMenu.style.transformOrigin = "top left";
process_array.push(menu_slant);
break;
case 35:
//Added the ability for paramaters, all push paramaters here are: function, menu_index, position, speed, tmp as flag for switching to next menu,
//process_index used to give the process index as refrence to delete..
window.alert(process_array.length);
process_array.push(new Array(menu_div_slide_out, child_index_amount - 1, 0, 0, 0, process_array.length-1));
break;
}
}
var initiate_all_processes = function() {
for (var i = 0; i < process_array.length; i++) {
//Added the ability for paramaters, considerer removing as its not used atm, or revising.
if (process_array[i] != undefined && process_array[i] != null && process_array[i] != "") {
if (process_array[i].length < 6) {
process_array[i]();
} else {
process_array[i][0](process_array[i][5]);
}
}
}
}
function menu_div_slide_out(process_index) {
/*process_array[process_index][
0 = function,
1 = current menu item (index length working backwards)
2 = position,
3 = speed,
4 = tmp,
5 = refrence to this process in array] */
//for debuging purposes to see if a ChildDiv is not devined, what process index is being pointed to.
//window.alert('Process index ' + process_index);
//!!!!!!!! You are probably mixing up how you are setting process index! try +1
process_array[process_index][2] += 3.5 + (process_array[process_index][3] * 1.7);
process_array[process_index][3] += (speed_modifier * .3);
childDivs[process_array[process_index][1]].style.left = process_array[process_index][2] + 'px';
if (process_array[process_index][2] > 100 && process_array[process_index][4] && process_array[process_index][1] > 0) {
// window.alert('CCC');
process_array[process_index][4] = true;
//Add another process at ever 100pxs
process_array.push(new Array(menu_div_slide_out, process_array[process_index][1] - 1, 0, 0, false, process_array.length-1));
//debugger;
} else
if (process_array[process_index][2] >= (900 - (process_array[process_index][2] / 20))) {
childDivs[process_array[process_index][1]].remove();
//process_array.splice(process_array[process_index][5], 1);
}
}
function menu_slant() {
rotate_return = rotate(rootMenu, .1 + (tmp1_speed), 27);
tmp1_speed += (speed_modifier * .5);
if (rotate_return === true) {
/////////////This can be unremoved because there is more animation, perhaps. or can be done in another key frame.
tmp1_speed = 0;
rotate_current_deg = 0;
remove_process(menu_slant);
} else {
if (rotate_return / 27 * 100 >= 60 && case3_flag < 0) {
case2_flag = frame;
}
}
}
var menu_child0 = function() {
childDiv_tmp1_position += 3 + (tmp1_speed * 1.7);
childDiv.style.top = childDiv_tmp1_position + 'px';
rotate(childDiv, .2 + (tmp1_speed), 170);
tmp1_speed += (speed_modifier * .7);
if (childDiv_tmp1_position / client_height * 100 >= 80 && case2_flag < 0) {
case2_flag = frame;
}
if (childDiv_tmp1_position >= client_height) {
childDiv.style.visibility = 'hidden';
tmp1_speed = 0;
childDiv_tmp1_position = 0;
rotate_current_deg = 0;
//may be bloated >>
remove_process(menu_child0);
}
}
function remove_process(index) {
var index_tmp = process_array.indexOf(index);
if (index_tmp >= 0) {
process_array.splice(index_tmp, 1);
}
}
function rotate(rotate_div, rotate_passed_deg, rotate_passed_deg_stop) {
rotate_current_deg += rotate_passed_deg;
rotate_deg = rotate_current_deg < rotate_passed_deg_stop ? rotate_current_deg : rotate_passed_deg_stop;
rotate_div.style.webkitTransform = 'rotate(' + rotate_deg + 'deg)';
rotate_div.style.mozTransform = 'rotate(' + rotate_deg + 'deg)';
rotate_div.style.msTransform = 'rotate(' + rotate_deg + 'deg)';
rotate_div.style.oTransform = 'rotate(' + rotate_deg + 'deg)';
rotate_div.style.transform = 'rotate(' + rotate_deg + 'deg)';
if (rotate_current_deg >= rotate_passed_deg_stop) {
return true;
} else {
return rotate_current_deg;
}
}
//main loop for the animation
var mainloop = function() {
processes_logic();
initiate_all_processes();
frame++;
}
var loop_interval = setInterval(mainloop, mainloop_frame_time);
</script>
I am trying to animate my website falling apart but I am having a hard time articulation this into code. I thought of running the animation in a loop, creating events at specific frames and reusing some codes as functions. I have a rotate function which works to rotate several things.
THE PROBLEM:
The problem I am having is sliding my menu items one at a time to the right. I want one to slide a bit and the next to start sliding after. I wrote a function to slide an item and then in that function it adds another process to an array for the next menu item to be called and run the same function (with passed interval of who is calling). I do not know how many menu items there will be, thats why I am trying to make it dynamic.
I can get it so that the first mwnu item falls, the menu falls by rotating it (some times if there is an error in the code then it wont rotate, but when there are no errors it works better).
The issue is sliding each menu item.
my website is here: http://clearlove.ca/89-404-error
Can any one help me with why this isnt working, and if there is a better way to do what I am trying to do?
I have image I am scrolling within a div.
It make sure the image is visible I am using
var isVisible = (
threshold.top >= -39 &&
threshold.bottom <= (window.innerHeight || document.documentElement.clientHeight)
);
What I am trying to do now is make sure that once the element is visible it is able to completely finish scrolling before going out of the view port.
I am thinking I can do this by effecting the speed value based on the the distance of the element from the top on the window. But I am having a very hard time doing this.
I am using .getBoundingClientRect() to get the distance the element is from the top of the viewport:
var threshold = document.getElementById('page-feature').getBoundingClientRect();
var thresholdY = threshold.top;
Below is my code so far:
function scrollImageInViewport() {
var threshold = document.getElementById('page-feature').getBoundingClientRect();
var thresholdY = threshold.top;
var isVisible = (
threshold.top >= -39 &&
threshold.bottom <= (window.innerHeight || document.documentElement.clientHeight)
);
if (isVisible && window.innerWidth > 550) {
scrollDir(thresholdY);
}
}
function scrollUp(thresholdY) {
if (thresholdCounter < maxScrollNegative) {
return;
} else {
pageScroll.setAttribute('style', '-webkit-transform:translate3d(0,' + (--thresholdCounter *speed) + 'px,0); -ms-transform:translate3d(0,' + (--thresholdCounter *speed) + 'px,0); transform:translate3d(0,' + (--thresholdCounter *speed) + 'px,0);');
}
};
function scrollDown(thresholdY) {
if (thresholdCounter > maxScrollPositive) {
return;
} else {
pageScroll.setAttribute('style', '-webkit-transform:translate3d(0,' + (++thresholdCounter *speed) + 'px,0); -ms-transform:translate3d(0,' + (++thresholdCounter *speed) + 'px,0); transform:translate3d(0,' + (++thresholdCounter *speed) + 'px,0);');
}
};
function scrollToTop(){
initScroll();
pageScroll.setAttribute('style', 'transform:translate3d(0,0,0);');
thresholdCounter = 0;
};
function scrollDir(thresholdY) {
var scroll = window.scrollY;
if(scroll > position) {
distanceFromTop(thresholdY);
scrollUp(thresholdY);
} else if (scroll < position ){
scrollDown(thresholdY);
}
position = scroll;
};
function distanceFromTop(thresholdY) {
if (thresholdY > 0) {
`enter code here`//set speed as distance from top /px of not shown content
speed = (scrollImageHeight - scrollVisibleHeight) / thresholdY;
}
};
function initScroll(){
position = window.scrollY;
pageScroll = document.getElementById('page-scroll');
scrollImageHeight = pageScroll.offsetHeight; //total height of scroll image
pagePanel = document.getElementById("pagePanel");
pageStyle = window.getComputedStyle(pagePanel,"");
size = pageStyle.getPropertyValue("height");
scrollVisibleHeight = parseInt(size, 10);//visible height of scroll image
scrollImageEnd = scrollImageHeight - scrollVisibleHeight;
maxScrollNegative = -scrollImageEnd / speed;
}
var speed;
var thresholdCounter = 0;
var maxScrollPositive = 0;
var position,
pageScroll,
scrollImageHeight,
pagePanel,
pageStyle,
size,
scrollVisibleHeight,
scrollImageEnd,
maxScrollNegative;
window.addEventListener('resize', scrollToTop);
document.addEventListener('scroll', scrollImageInViewport);
window.addEventListener('load', initScroll);
This is what I ended up with:
var featurePage = document.getElementById('page-feature')
var pageScroll = document.getElementById('page-scroll');
var startP, // where animation needs to begin
endP, // where animation needs to end
diff; // visible element size
function getElementOffset(){ //init
var de = document.documentElement;
var box = featurePage.getBoundingClientRect();
var top = box.top + window.pageYOffset - de.clientTop;
var bottom = box.bottom + window.pageYOffset - de.clientTop;
var winHight = window.innerHeight;
diff = bottom - top;
var elPadding = (winHight - diff);
startP = top - elPadding;
endP = bottom - elPadding;
scrollImage()
}
function scrollImage(){
var scrollImageHeight = pageScroll.offsetHeight;
var scrollPos = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
var s1 = scrollPos - startP;
var realPos = -s1/diff;
var lengthLeft = scrollImageHeight - (diff)
if ( realPos < 0.09 && realPos > -1){
pageScroll.setAttribute('style', '-webkit-transform:translate3d(0,' + (realPos * lengthLeft) + 'px,0); -ms-transform:translate3d(0,' + (realPos *lengthLeft) + 'px,0); transform:translate3d(0,' + (realPos *lengthLeft) + 'px,0);');
}
}
window.addEventListener('resize', getElementOffset);
document.addEventListener('scroll', getElementOffset);
I need a photography gallery to display in 3 rows, each row showing different number of images. Not all images have the same width. When the screen resizes I want more images to show, but in the same ratio (grow to 3/5/4, 4/6/5, etc...). The ratio should be like this (brackets represent an image):
[][]
[][][][]
[][][]
Visual example here.
It was partly working except for the offset. I tried to write an offset loop, and now it's not working at all. Here is the code:
<script>
jQuery(document).ready(function() {
jQuery('.gallery').wrap('<div class="gal-wrapper" />');
resizeGallery("#gallery-1",2);
resizeGallery("#gallery-2",4);
resizeGallery("#gallery-3",3);
});
jQuery(window).resize(function() {
resizeGallery("#gallery-1",2);
resizeGallery("#gallery-2",4);
resizeGallery("#gallery-3",3);
});
function resizeGallery(gall, initpos){
var x = 0;
var y = 0;
var accum_width = 0;
var final_width = accum_width;
var offset = initpos;
var wW = jQuery(window).width()-jQuery("#nav").width();
while(accum_width < wW){
var new_width = jQuery(gall).find("img.attachment-medium:eq("+x+")").width();
if((accum_width + new_width) > wW){
break;
}else{
accum_width += new_width+4;
}
x++;
}
/* worked partly to this point... onto the offset! */
while(y < offset){
var subtract_width = jQuery(gall).find("img.attachment-medium:eq("+x+")").width();
final_width -= subtract_width+4;
y++;
x--;
}
jQuery(gall).parent().width(final_width);
}
</script>
Here is a jsfiddle example.
Your working JS fiddle
In case That fiddle link doesn't work...
jQuery(document).ready(function() {
jQuery('.gallery').wrap('<div class="gal-wrapper" />');
var picCount = resizeGallery("#gallery-2", Number.POSITIVE_INFINITY);
resizeGallery("#gallery-3", picCount-1);
resizeGallery("#gallery-1", picCount-2);
});
jQuery(window).resize(function() {
var picCount = resizeGallery("#gallery-2", Number.POSITIVE_INFINITY);
resizeGallery("#gallery-3", picCount-1);
resizeGallery("#gallery-1", picCount-2);
});
function resizeGallery(gall, picCount) {
var x = 0;
var y = 0;
var accum_width = 0;
var wW = jQuery(window).width() - jQuery("#nav").width();
while (accum_width < wW && x < picCount) {
var new_width = jQuery(gall).find("img.attachment-medium:eq(" + x + ")").width();
if ((accum_width + new_width) > wW) {
break;
} else {
accum_width += new_width + 4;
}
x++;
}
jQuery(gall).parent().width(accum_width);
return x;
}