jQuery move background to follow element positioned using CSS Animations - javascript

I got an application where I'm moving an image around the page using CSS3 Animations the idea is you click a button and the next animation runs and this way the "sprite" moves around a map.
However on mobile I was asked to keep the size of the map the same as desktop but instead move the map instead of the sprite, my question is how can I make that work?
My current (really early) code looks like this:
$(document).on("boatAnimationStarted", function(event) {
window.isAnimating = true;
var boatElement = $("#boat-sprite");
var backgroundElement = $("#background");
var backgroundWidth = backgroundElement.width();
var backgroundHeight = backgroundElement.height();
var windowSize = { width: $(window).width(), height: $(window).height() };
var originalOffset = boatElement.offset();
window.animationInterval = setInterval(function() {
var boatOffset = boatElement.offset();
var working = {
top: originalOffset.top - (boatOffset.top / 2),
left: originalOffset.left - (boatOffset.left / 2),
}
$("#background").offset(working);
}, 10);
});
This does manage to move it somewhat but it doesn't seem to be exact and isn't really accounting for the offset of the #background element when it changes position.
So I'm guessing I should do everything relative to the Background image (which is around 1200w X 421h)
So to do that you would do something like this i'm guessing
var relativeOffset = {
top: boatOffset.top - backgroundElement.offset().top,
left: boatOffset.left - backgroundElement.offset().left
}
And I would in theory get the offsets of the sprite relative to the large background image as opposed to the mobile viewport. But then how would I go about moving the background?
Sorry if it's a simple question but it's the first time I've ever had to work with this kind of stuff so I'm a bit confused.

Related

How can I make a circular page? (when scrolled to the end of page content, page adds the beginning of conten to the bottom and so forth)

I am currently making a portfolio, in which I have Comic-books that use circular storytelling - meaning the story always repeats itself. Where it ends it begins from new.
I know how vertical scrolling works, but now I wish to have the page infinitely scroll as you could read the comic over and over. Ideally, this would work seamlessly (without skipping around inside the page).
Can someone please point me in the right direction as to how I can do this with HTML and CSS, or if need be also with javascript?
Thank you very much.
This was actually the thing I was looking for:
http://jsfiddle.net/howderek/N9PWn
Thank You Mara
window.verticalScroller = function($elem) {
var top = parseInt($elem.css("top"));
var temp = -1 * $('#verticalScroller > div').height();
if(top < temp) {
top = $('#verticalScroller').height()
$elem.css("top", top);
}
$elem.animate({ top: (parseInt(top)-60) }, 600, 'linear', function () {
window.verticalScroller($(this))
});}
$(document).ready(function() {
var i = 0;
$("#verticalScroller > div").each(function () {
$(this).css("top", i);
i += 60;
window.verticalScroller($(this));
});});

How to implement autoscroll to follow my div

I've looked at several tutorials online and a few similar questions on SO but not been able to work out how to make the screen autoscroll left and right so that my #sheep stays in the centre of the screen.
I'm using javascript and jquery to move a simple div across the screen.
Here's my jsfiddle
http://jsfiddle.net/JosephByrne/CkkVr/
What's the best method of making the screen follow my div?
I think you're trying to move the wrong element left/right. I think you need to leave your sheep in the middle of the screen then move the background.
Something like:
var walkLeft = function() {
$('#background').animate({left:"-=10px",top:"-=2px"}, 100);
$('#background').animate({left:"-=10px",top:"+=2px"}, 100);
};
var walkRight = function() {
$('#background').animate({left:"+=10px",top:"-=2px"}, 100);
$('#background').animate({left:"+=10px",top:"+=2px"}, 100);
};
http://jsfiddle.net/CkkVr/22/ (you'll need to "jump right" to see the sheep), but you get the general idea!
You need something similar to this:
function scrollContainer() {
var $sheep = $("#sheep");
$("body").scrollLeft($sheep.position().left + $sheep.width());
}
That utilizes jQuery's scrollLeft() function as well as the position() function (on the sheep).
You just need to keep messing with the math until it works out properly...
I've implemented it on the "jump" functions here:
http://jsfiddle.net/Dxe8a/11/
function scrollContainer() {
var $sheep = $("#sheep");
var $body = $("body");
var windowWidthOver2 = ($(window).width()/2);
var pos = $sheep.position().left + windowWidthOver2 - $sheep.width() - 80;
if($body.width() <= (pos + windowWidthOver2 - $sheep.width() - 80)) {
$body.width($body.width() + windowWidthOver2);
}
$body.scrollLeft(pos);
}
You should alter it so that it looks a bit better, but at least it follows your sheep somewhat.
P.S. it works better in fiddle if you view it in "/show": http://jsfiddle.net/Dxe8a/11/show

Do not execute jQuery script if CSS is of particular value

On my website, I have a sidebar DIV on the left and a text DIV on the right. I wanted to make the sidebar follow the reader as he or she scrolls down so I DuckDuckGo'ed a bit and found this then modified it slightly to my needs:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(function(){
var $sidebar = $('#sidebar'),
sidebarOffset = $sidebar.offset(),
$window = $(window),
gap = $('#header').css('marginBottom').replace(/[^-\d\.]/g, ''),
distance = ($window.scrollTop()) - (sidebarOffset.top - gap),
footerHeight = $('#footer').outerHeight();
$window.scroll(function(){
distance = ($window.scrollTop()) - (sidebarOffset.top - gap);
if ( distance > 0 ) {
$sidebar.css({'top': gap + 'px', 'position' : 'fixed'});
} else {
$sidebar.css({'top': '0', 'position': 'relative'});
}
})
});
});//]]>
</script>
And it works just like I want it to. However, my website uses Skeleton framework to handle responsive design. I've designed it so that when it goes down to mobile devices (horizontal then vertical), sidebar moves from being to the left of the text to being above it so that text DIV can take 100% width. As you can probably imagine, this script causes the sidebar to cover parts of text as you scroll down.
I am completely new to jQuery and I am doing my best through trial-and-error but I've given up. What I need help with is to make this script not execute if a certain DIV has a certain CSS value (i.e. #header-logo is display: none).
Ideally, the script should check for this when user resizes the browser, not on website load, in case user resizes the browser window from normal size to mobile size.
I imagine it should be enough to wrap it in some IF-ELSE statement but I am starting to pull the hair out of my head by now. And since I don't have too much hair anyway, I need help!
Thanks a lot in advance!
This function will execute on window resize and will check if #header-logo is visible.
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
// Your code
}
});
I think you need to check this on load to, because you don't know if the user will start with mobile view or not. You could do something like this:
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
// Your code
}
}).resize();
This will get executed on load and on resize.
EDIT: You will probably need to turn off the scroll function if #header-logo is not visible. So, instead of create the function inside the scroll event, you need to create it outside:
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
var $sidebar = $('#sidebar'),
sidebarOffset = $sidebar.offset(),
$window = $(window),
gap = $('#header').css('marginBottom').replace(/[^-\d\.]/g, ''),
distance = ($window.scrollTop()) - (sidebarOffset.top - gap),
footerHeight = $('#footer').outerHeight();
function myScroll() {
distance = ($window.scrollTop()) - (sidebarOffset.top - gap);
if ( distance > 0 ) {
$sidebar.css({'top': gap + 'px', 'position' : 'fixed'});
} else {
$sidebar.css({'top': '0', 'position': 'relative'});
}
}
$window.on('scroll', myScroll);
} else {
$(window).off('scroll', myScroll);
}
});
Didn't test it, but you get the idea.
$("#headerLogo").css("display") will get you the value.
http://api.jquery.com/css/
I also see you only want this to happen on resize, so wrap it in jquery's resize() function:
https://api.jquery.com/resize/

Decrease image size automatically over a certain amount of time

I am looking for a script but I'm not sure what to look for.
I have a webpage that has the body tag with a background image.
body {
background: url(eye.gif)repeat;
background-size:91px 91px;
}
What I am hoping to achieve is when the page loads it shows the background image as 991px then slowly decrease by 10px over a set time until the original size of 91px.
I'm not sure if there is away to do this, or even another way that when the page is loaded it is zoomed in and then zooms out automatically over time.
Basically when the page is loaded you will see the image twice and then over time you will see more and more.
Can anyone point me in the right direction.
if you use background-size your using css3 and so you can use keyframes
no javascript needed.
#-webkit-keyframes bganimation{
0%{background-size:991px 991px;}
100%{background-size:91px 91px;}
}
body{
background: url(eye.gif)repeat;
background-size:91px 91px;
-webkit-animation:bganimation 20s linear; // 20s = 20 seconds
}
for more support you need to add the other specific prefixes (-moz,-ms..)
Here is a sample using JQuery:
http://jsfiddle.net/frUvf/16/
$(document).ready(function(){
$('body').animate({'background-size':'10000px'}, 50000);
})
Using vanilla JS:
var lowerBound = 250,
step = 10,
duration = 1000,
image = document.getElementById('image');
(function resizer () {
if (image.clientWidth > lowerBound) {
image.style.width = image.clientWidth - step + 'px';
var timer = setTimeout(resizer, duration);
} else {
clearTimeout(timer);
}
}());
Just change the lowerBound/step/duration variables to whatever you need them to be.
Fiddle
with jquery:
var body = $('body');
var zoom = 2;
var interval_zoom = 0.5;
var time_interval = 90000;
setInterval(function(){
body.css("zoom", zoom);
zoom = zoom - interval_zoom;
if(zoom<=1)
clearTimeout(this);
}, time_interval )
Zoom and interval must be calculated
You could use Javascript for the animation or could take a look at CSS3 Transformations: http://web.archive.org/web/20180414114433/http://www.pepe-juergens.de/2013/02/css3-transform/

Getting Coordinates of an element on page scroll

I am having this problem where i have a set of 6 UL's having a common class x.Each of them consist of a specific section of the page.Now i have 6 menus that are related to each of the section.What i have to do is highlight the menu when its related section is in users view.
For this i thought that may be jQuery position(); or offset(); could have helped but they give the top and left of the element.I also tried using jQuery viewport plugin but apparently view port is big it can show more than one UL at a time hence i cant apply element specific logic here.I am not familliar to this but does anything changes of an element on scrolling?If yes then how to access it?
Please share your views.
Regards
Himanshu Sharma.
Is very easy to do it using jQuery and a dummy fixed HTML block that helps you find the current position of the viewport.
$(window).on("scroll load",function(){
var once = true;
$(".title").each(function(ele, index){
if($(this).offset().top > $("#viewport_helper").offset().top && once){
var index = $(this).index(".title");
$(".current").removeClass('current')
$("#menu li").eq(index).addClass('current')
once = false;
}
});
})
Check out a working example: http://jsfiddle.net/6c8Az/1/
You could also do something similar with the jQuery plugin, together with the :first selector:
$(window).on("scroll load",function(){
$(".title:in-viewport:first").each(function(){
var index = $(this).index(".title");
$(".current").removeClass('current')
$("#menu li").eq(index).addClass('current')
});
})
You can get the viewport's width and height via $(document).width() and $(document).height()
You can get how many pixels user scrolls via $(document).scrollTop() and $(document).scrollLeft
Combining 1 and 2, you can calculate where the viewport rectangle is
You can get the rectangle of an element using $(element).offset(), $(element).width() and $(element).height()
So the only thing left to you is to determine whether the viewport's rectangle contains (or interacts) the elements's rectangle
So the whole code may look like:
/**
* Check wether outer contains inner
* You can change this logic to matches what you need
*/
function rectContains(outer, inner) {
return outer.top <= inner.top &&
outer.bottom >= inner.bottom &&
outer.left <= inner.left &&
outer.right >= inner.right;
}
/**
* Use this function to find the menu related to <ul> element
*/
function findRelatedMenu(element) {
return $('#menu-' + element.attr('id'));
}
function whenScroll() {
var doc = $(document);
var elem = $(element);
var viewportRect = {
top: doc.scrollTop(),
left: doc.scrollLeft(),
width: doc.width(),
height: doc.height()
};
viewportRect.bottom = viewportRect.top + viewportRect.height;
viewportRect.right = viewportRect.left + viewportRect.width;
var elements = $('ul.your-class');
for (var i = 0; i < elements.length; i++) {
var elem = $(elements[i]);
var elementRect = {
top: elem.offset().top,
left: elem.offset().left,
width: elem.width(),
height: elem.height()
};
elementRect.bottom = elementRect.top + elementRect.height;
elementRect.right = elementRect.left + elementRect.width;
if (rectContains(viewportRect, elementRect)) {
findRelatedMenu(elem).addClass('highlight');
}
}
}
$(window).on('scroll', whenScroll);
Let's see if i understood well. You have a page long enough to scroll, and there is an element that when it appears in the viewport, you wanna do something with it. So the only event that's is triggered for sure on the time the element gets in the viewport is the 'scroll'. So if the element is on the page and the scroll is on the viewport, what you need to do is bind an action to the scroll event to check if the element is in the view each time the event is trigger. Pretty much like this:
$(window).scroll(function() {
check_element_position();
});
Now, in order for you to know if the element is in the viewport, you need 3 things. The offset top of that element, the size of the viewport and the scroll top of the window. Should pretty much look like this:
function check_element_position() {
var win = $(window);
var window_height = win.height();
var element = $(your_element);
var elem_offset_top = element.offset().top;
var elem_height = element.height();
var win_scroll = win.scrollTop();
var pseudo_offset = (elem_offset_top - win_scroll);
if (pseudo_offset < window_height && pseudo_offset >= 0) {
// element in view
}
else {
// elem not in view
}
}
Here, (elem_offset_top - win_scroll) represent the element position if there was no scroll. Like this, you just have to check if the element offset top is higher then the window viewport to see if it's in view or not.
Finally, you could be more precise on you calculations by adding the element height (variable already in there) because the code i just did will fire the event even if the element is visible by only 1 pixels.
Note: I just did that in five minutes so you might have to fix some of this, but this gives you a pretty darn good idea of what's going on ;)
Feel free to comment and ask questions

Categories

Resources