Images not stacking correctly - javascript

I've been making a simply jellyfish game on a website where you must prevent jellyfish from reaching the top by clicking on them and I've run into a problem I cant figure out. You are able to spawn jellyfish in the game (for now) and they will randomly position themselves across a playing field and they should stack on top of each other as each one has a seperate z-index. They are randomized by randomizing their left margins (This works fine). However, when I click on a jellyfish to delete it, all the other images jump to the left, as if one part of the jellyfish wasn't allowed to stack at all. Here is the current js method that controls the spawning of a jellyfish. Thank you guys in advance :)
var spawnJelly = function(jellyType) {
//57 is the width of the jellyfish picture.
var jelliesSpawnPosition = Math.random()*1000 - 57;
jelliesSpawned++
var newJelly = document.createElement("img");
newJelly.setAttribute('src', "https://www.googledrive.com/host/0B-IaOP2CvHbffk56ZWFrUExfX1ZVNWZ0RmRmYU0tMHVoUHVDZzJ1NzhRV2l0c01kSENnNWc/jelly"+jellyType+".png");
document.getElementById("playingField").appendChild(newJelly);
newJelly.addEventListener("click", deleteJelly);
// jelliesSpawned is a global variable
newJelly.setAttribute('style', 'left: '+jelliesSpawnPosition+'px; z-index: '+jelliesSpawned);
console.log("jellyfish created!");
};
Here is the method for deleteJelly:
function deleteJelly() {
this.parentNode.removeChild(this);
console.log("Jellyfish removed!")
}
Here is the link to the current website I am making this jellyfish game on.
http://atestingsite.x10host.com/cgi-bin/jellyfishGameC.html

You are using position relative, and that means the images take the physical space and will cause page reflow when you remove them. You should change your positioning to absolute (and set the jelly fish container to position relative per Jan).

Related

How to increase speed of mousemove/clientX/Y and applying a transform?

I have built a WordPress theme. I came across a website that created a div to follow the user's cursor. The div was enlarged smoothly when the user hovers over a button or a link.
I want to add this nice functionality as an optional feature.
I added a div to the web page, #ambition_cursor and added some basic styling. The div now shows like a blue circle. The circle has position fixed to the top left corner of the site. The position can be changed by adding a CSS translate property.
I managed to make it work with the following code:
var ambition_cursor = document.getElementById("ambition_cursor");
function ambition_mouse(e) {
var ambition_cursor_x = e.clientX; // Get the horizontal coordinate
var ambition_cursor_y = e.clientY; // Get the vertical coordinate
var ambition_cursor_pos = `translate(${ambition_cursor_x}px, ${ambition_cursor_y}px)`;
ambition_cursor.style.transform = ambition_cursor_pos;
}
window.addEventListener('mousemove', ambition_mouse);
The big downside here is the lag (?). There's quite a big delay, especially when moving the mouse around very fast. You can try it out on this site. I also put the situation in a JSFiddle; although the delay doesn't really happen there.
I didn't apply yet much styling (the default cursor is visible, so you can get a better idea of the real position). I first want this to work better, before I spent much time on that.
How can I increase the speed of this, so that the div position follows the mouse more accurately? I'm a beginner, so I don't really know which JavaScript optimisations I should make.
Current code is JavaScript, but jQuery is also an option.
Many thanks in advance!
Update: example how it looks on my computer.
All elements on the page have a transition applied. Remove/override this style and the delay goes away (tested).
As an alternative to the great answer of Joseph Atkinson:
var ambition_cursor = document.getElementById("ambition_cursor");
function ambition_mouse(e) {
ambition_cursor.style.left = e.clientX + 'px'; // Get the horizontal coordinate
ambition_cursor.style.top = e.clientY + 'px' ; // Get the vertical coordinate
}
window.addEventListener('mousemove', ambition_mouse);
See: https://levelup.gitconnected.com/use-javascript-to-make-an-element-follow-the-cursor-3872307778b4
I visited the site example, cracked open the dev console, and found throttled(20, ambition_mouse) It is not a performance issue, and the solution is to not throttle the events. It was too smooth to be a performance issue, which gave me the first clue it had to be an accidental/deliberate effect.

Change text size on scroll

I would like to achieve the following:
On a mobile device, when someone starts scrolling from the top, a text starts to shrink down, and after a given amount, it takes its final size and stays like so for the rest of the page. The idea is that I have a Company name in the middle of the screen, and on scroll, it shrinks to the top left corner of the screen, and a menu bar appears behind it, and the Company name becomes the logo on the menu bar. The menu bar's background is the Hero image of the page. Here is my code:
window.onscroll = scrolled
function scrolled(){
let fromTop = window.scrollY
if (fromTop < 300) {
heroText.style.fontSize = `${2 - fromTop/160}em`
hero.classList.remove('hero-fixed')
heroNav.classList.remove('hero-nav-fixed')
heroText.classList.remove('h1-fixed')
heroImg.classList.remove('hero-img-fixed')
} else {
hero.classList.add('hero-fixed')
heroNav.classList.add('hero-nav-fixed')
heroText.classList.add('h1-fixed')
heroImg.classList.add('hero-img-fixed')
}
if (fromTop > 360) {
heroNav.classList.add('nav-mobile', 'hidden')
intro.classList.add('intro-fixed')
hamburger.classList.remove('hidden')
} else {
hamburger.classList.add('hidden')
heroNav.classList.remove('nav-mobile','hidden')
intro.classList.remove('intro-fixed')
}
}
}
It works, but I have to adjust for every screen size I want to support, and it is extremely laggy! It is probably a very wrong way to do it, so could someone help me make it more efficient and less laggy on mobile devices?
My guess is that the constant resizing of the text is one of the problems, as well as the height change of the hero image. I play with position fixed, and padding-top changes in the CSS to compensate the disappearing (becoming fixed positioned) elements.
Could some library, like RxJS help, or is there a VanillaJS elegant solution as well?
To make this more efficient in the Javascript side, you could use something like lodash's debounce.
Changing layout can be a very resource intensive operation so you might want to try leaving the element fixed position all the time and only adjusting its size (and/or the size of its parents) with the CSS transform property. scale() would work quite nicely here.

How can I create overlapping images that reveal themselves as you scroll

I am looking to create a scrolling effect similar to that shown here: http://www.seaham-hall.co.uk/
However I am unable to achieve the desired effect, and inspecting the sites code gives me no hints. Quite difficult to google for as it is also quite difficult to describe. The closest I can get to finding a solution is this JSFiddle:
http://jsfiddle.net/xtyus/1/
(function($){
/* Store the original positions */
var d1 = $('.one');
var d1orgtop = d1.position().top;
var d2 = $('.two');
var d2orgtop = d2.position().top;
var d3 = $('.three');
var d3orgtop = d3.position().top;
var d4 = $('.four');
var d4orgtop = d4.position().top;
/* respond to the scroll event */
$(window).scroll(function(){
/* get the current scroll position */
var st = $(window).scrollTop();
/* change classes based on section positions */
if (st >= d1orgtop) {
d1.addClass('latched');
} else {
d1.removeClass('latched');
}
if (st >= d2orgtop) {
d2.addClass('latched');
} else {
d2.removeClass('latched');
}
if (st >= d3orgtop) {
d3.addClass('latched');
} else {
d3.removeClass('latched');
}
if (st >= d4orgtop) {
d4.addClass('latched');
} else {
d4.removeClass('latched');
}
});
})(window.jQuery);
However I am not sure that is going in the right direction, this pulls images up and covers the previous image, but notice on the Seaham Hall site the images don't appear to move up at all, they are stationary and become revealed as you scroll.
How do I recreate this effect? My initial thought was to have the first image shrink as you scroll from 1000px down to 0px, and the second image grow to 1000px, and as you continue to scroll this image then shrinks and the third grows, and so on. However this means that after the first image all the other images have a starting size of 0px and there would technically be no scrolling on the page to begin with, so that is an issue.
My second thought is that perhaps the second image is fixed to the page, the first image slides up revealing the second as you scroll, the second image would not appear to move. Once the first image has gone off the top of the page the second image is detached from the page and allowed to move up with scrolling, while the third image is attached and revealed as the second moves up, this would give the exact effect seen in the Seaham website but I have no clue of it is the correct answer.
If anyone can point me to tutorials or a JSFiddle with a basic concept I can probably figure it out from there. Just stumped what direction to approach this from.
That's a nice effect. Here's one way to do it.
Put each image in a fixed position div, which takes up the entire viewport (initially) and has overflow:hidden.
Set each div's z-index to be higher than the next div's.
As the window scrolls, adjust the height of the divs as a function of the window height times the div's position (index) in the DOM, minus the window's scrollTop:
$(window).scroll(function() {
$('.D').each(function(index) {
$(this).css({
height: $(window).height()*(index+1) - $(window).scrollTop()
});
});
});
Additional content will need a higher z-index than the image divs. And note that z-index works with positioned elements only.
Fiddle
Your desired effect isn't technically a parallax background, but it's close enough that parallax jQuery frameworks should work for you.
I would suggest you research jQuery Parallax plugins as they'll likely provide the functionality you'd like without much custom work. Of course since you're dealing with large images it's also best to keep an eye on the resource management; a good plugin should be fairly efficient but others may be slow or resource intensive.
Check this jquery plugin:ScrollMagic
usage: taken from github
The basic ScrollMagic design pattern is one controller, which has several scenes attached.
Each scene has a definite start and end position and defines what happens when the container is scrolled to the specific offset.
/*
Basic workflow example
*/
// init controller
var controller = new ScrollMagic();
// assign handler "scene" and add it to controller
var scene = new ScrollScene({duration: 100})
.setPin("#my-sticky-element") // pins the element for a scroll distance of 100px
.addTo(controller); // add scene to controller
// adding multiple scenes at once
var scene2 = new ScrollScene();
var scene3;
controller.addScene([
scene2,
scene3 = new ScrollScene({duration: 200}), // add scene and assign handler "scene2"
new ScrollScene({offset: 20}) // add anonymous scene
]);

Using javascript to find the page number of the current view page in an iboooks epub

I am building a lightbox style div element for an ibooks epub. I want the div to be displayed on the current page being viewed at the time. If the image is on page two of the ebook, I want the lightbox to showup on page two. I have the div width and height set to fill the screen.
document.getElementById("LightBoxDiv").style.width=window.innerWidth+"px";
document.getElementById("LightBoxDiv").style.height=window.innerHeight+"px";
I can manualy set a fixed top value of the div if I know which page number an image is on. My device has a 460px height on the window. So for an image on page two, the top should then be 460 which is the beginning of the 2nd page.
document.getElementById("LightBoxDiv").style.top="460px";
However, as ebooks are dynamic in that the user can change the size of the text larger or smaller, the page upon which something might fall changes. I need a way to set the top dynamically based upon the current page. If I know the current page number being viewed, I can set the div top to
var lighboxHeight = (pagenumber-1)*window.innerHeight;
I tried using the window.pageYOffset to calculate the current page, but this always gives a 0 value as the page does not scroll in an ebook. Unfortunately, I can find no documentation or any reference describing how to use javascript to access the page numbers. Does anyone have any idea how to access or find the current page number in an ibooks epub using javascript?
Thanks,--christopher
I believe I found the solution. This question/answer helped a lot.
//window height
var winHeight = window.innerHeight;
//top of object to be placed in the lightbox
//can be any object
var curOjbTop = document.getElementById(svgId).getBoundingClientRect().top;
//body y value
var bodyTop = document.body.getBoundingClientRect().top;
//amount the object is shifted vertically downward from the top of the body element
var offset = curObjTop - bodyTop;
//page number of the object
//this is actually 1 less than the true page number
//it basically starts the page count at 0, but for actual page number add 1
var curPage = Math.floor(offset/winHeight);
//this sets the top edge of the lightbox at y=0 on the page the item is on
var lightboxTop = curPage*winHeight;
document.getElementById("LightBoxDiv").style.top=lightboxTop;
My lightbox div covers the entire viewing area, but if you wanted a smaller one that was centered, you would need to add an additional half of the window height and then set the top margin to be half the negative amount of the height you wanted.
For example if the light box was 200 x 200, then your lightboxtop would be
var lightboxTop = (curpage*winHeight)+(winHeight*.5);
var topMargin = "-100px";
It may need to be tweeked some, but overall it should work to determine a page number.

Creating an Expanding DIV/Canvas with Horizontal Scrolling with Wheel JavaScript

Ok - here is what I am trying to do. I was looking online for a cool timeline that I can purchase - allowing zoom in zoom out, posting of events on it, and so on. However, all the examples I found are either too expensive or just downright useless.
So, I have decided to create my own, but there are two elements that I am having trouble with.
1) Converting the wheel scroll to left-right scrolling (so not up-down). I can't seem to find an easy and quick way to do this.
But, more importantly..
2) I need the area I will be showing the timeline on to automatically expand as I go about my scrolling. So, if I scroll down, it will add an "equivalent" area on the right, and down, on the left. So I was thinking like making an iFrame (already use these) and when you scroll it just adds more "timeline" on the left or the right, loads what ever it needs to load from the DB/list of events, and so on, ad infinitum, thus creating an ever-expanding list of blocks that are time-sized.
If I can do the two things above, then I am set - the rest (loading/positioning) I can figure out - just these two things are eluding my imagination and ability to find an answer.
Basically you need a horizontal infinite scroll script.
Take this plugin I wrote:
$.fn.hScroll = function( options )
{
function scroll( obj, e )
{
var evt = e.originalEvent;
var direction = evt.detail ? evt.detail * (-120) : evt.wheelDelta;
if( direction > 0)
{
direction = $(obj).scrollLeft() - 120;
}
else
{
direction = $(obj).scrollLeft() + 120;
}
$(obj).scrollLeft( direction );
e.preventDefault();
}
$(this).width( $(this).find('div').width() );
$(this).bind('DOMMouseScroll mousewheel', function( e )
{
scroll( this, e );
});
}
Initialize it with:
$('body').hScroll();
Makes your website a horizontally scrollable website.
Your content div must be wider than your body (ex. 3000px).
As for the infinite scrolling effect you pretty much gotta do that your self because I can't know what kind of data you'll input. But I'll explain.
Your children elements in the content div must be floated to left. (every new appended div will not go to new line).
Set an interval to check if the user's scrollLeft position is near the end of the content (just like pinterest and similar site).
function loadNewData(){ /* Your search for data and update here. */ }
setInterval('loadNewData', 500);
search for new data according to your last one with AJAX. When you get new data, append it into your content div (in a div that's floated left, as I wrote previously), and mark it as your last item.
Maybe you could use your ID to mark the last item on it's div.
<div data-id="467" class="item"> // your data here </div>
You can fetch it with
$('.item:last').attr('data-id');
with jQuery.

Categories