(js) moving div x pixels smoothly with jquery or similar? - javascript

I have an image that when clicked should move a div up ~200px, I have it set through jquery to modify css without isssue but it doesn't look as 'clean' or smooth as i've seen on other websites.
Forgive me but i've been searching for a few hours and can't find the function/method to do this, I figured fadein/out would do this but i'm fairly sure it cannot.
Could anyone take a moment to point me in the right direction? Thank-you.
EDIT: After writing this I thought maybe I should quickly incrementally change the css via jquery to simulate a low-fps 'glide' .. hopefully there is an easier way
EDIT2: Currently use this, looking for a way to do it 'smoothly' if that even makes sense
$('#Table_Topbar').hide();
var pix = "px";
var fix = $('#Table_Middle1').css('top');
var fix2 = fix.replace('px','');
var fixsub = (fix2 - 200);
var fixstring = fixsub.toString();
var fixconca = fixstring.concat(pix);
$('#Table_Middle1').css('top',fixconca);

If you want to do this using only Javascript, you could also simply use an interval to update the css every xx number of milliseconds, for 60fps you'd use 16. (This is not the best way)
var i = parseInt($("#Table_Middle1").css("top"));
var animationLoop = setInterval(function() { i += 10; $("#Table_Middle1").css("top", i + "px"); }, 16);
A simpler way would be to use jQuery's animate api: http://api.jquery.com/animate/. (this is the most cross-browser friendly way)
$('#Table_Middle1").animate({top: "-=200px"}, 1000); // take 1 second to move up 200px
You could also use a CSS3 transition to accomplish the same thing, and reduce your JS to a simple class toggle (This is the most "modern" way)
jQuery:
$('#Table_Middle1").addClass("class-to-trigger-animation");
css:
#Table_Middle1 { top: 500px; transition: top 1s ease; }
#Table_Middle1.class-to-trigger-animation { top: 300px }
If you want more complex animations, you could consider a library like Greensock.

You could use a combination of js (jQuery) and CSS here, eg.
CSS:
.switch {position: absolute; top: 0; left: 0; transition: top 1s}
.switch.active {top: 160px}
jQuery:
$('.switch').click(function(){
$(this).toggleClass('active');
});
Check out the fiddle here: http://jsfiddle.net/pavkr/Lu7q2c1r/1/
You would need to adjust the parameters however, this is just a quick example.

Related

Moving Background stutter/lag

I'm having trouble getting a website to work properly. It has numerous moving backgrounds and makes use of the css-invert filter.
Please have a look here:
http://epicstudios.de/blackwhite/
My problem is, that even average computers have problems processing the moving background, which is essential for the effect I want the site to have. I figured that the problem might be that I have too many divs with moving backgrounds, but since these Divs have different, inverted background-images, I can't just leave them transparent. Or is there a way to use the invert-filter without giving the div a background-image, so that it inverts the content of the div beneath it? I hope thats clear.
My script for the moving background looks like this:
(function($) {
var x = 0;
var y = 0;
var bg = $("body,.overlay,.center_cirlce,.left_circle,.right-circle,.enter,.enter_outer,.enter_inner");
bg.css('backgroundPosition', x + 'px' + ' ' + y + 'px');
window.setInterval(function() {
bg.css("backgroundPosition", -x + 'px' + ' ' + -y + 'px');
y++;
}, 70);
})(jQuery);
I would like to know, if there is a way to reduce the CPU usage or whatever makes it stutter that awfully, without having to give up the effects I'm aiming for... Or whether I have bad programming somewhere, which I should change to improve performance.
Thank You!
Well, animating background-position is always a bad idea. Especially on huge images like these. Try to put the background images in their own container and animate that container with transform: translate() or even transform: translate3d(). It'll be much much smoother.
If you want to do it with JS i can recommend Greensocks TweenMax Animation library. It's damn fast and it'll use CSS transforms when available and fall back if not.
And adding backface-visibility: hidden to your animated elements will smooth things out too. Problem is, it seems you're using backface-visiblity for that effect on your site. To make things perform better I'd advice you rethink your structure and use animations with CSS transform as much as possible.

Javascript: Check collision between two divs

Is there any way to check, if DIV with name for example "character" is overlaping DIV with name "ground" ?
I want to do this with clean Javascript, I know that jQuery is better, but that's what I don't want.
I saw this post: check collision between certain divs? , but it does not return anything.
Thanks for help.
First, I'd suggest you check out the HTML5 canvas element, as by the sounds of it, you want to make a game, and the canvas is great for that ;)
But, to answer your question, you could create or get div elements with document.createElement() or getElementById() respectively, and get their style properties either by getting their JS-set values (element.style) or use getComputedStyle if you'd prefer to set initial values in CSS.
Make sure that, however you get these CSS properties, they'll need to be parsed into something that JS can digest. For integer-based positions, parseInt() usually does the trick.
Next, you do the math. In this case, you'd want to see if the character div's top, plus its height, is greater than the top position of the ground. If it is, it has collided.
To set the style back to the div, you can just set the style property.
Here's an example (copied from this fiddle):
var character = document.getElementById("character");
var ground = document.getElementById("ground");
//We could use getComputedStyle to get the style props,
//but I'm lazy
character.style.top = "10px";
character.style.height = "40px";
ground.style.top = "250px";
//For every 33ms (about 30fps)
setInterval(function(){
//Get the height and position of the player
var charTop = parseInt(character.style.top),
charHeight = parseInt(character.style.height);
//and the top of the ground
var groundTop = parseInt(ground.style.top);
//linear gravity? Why now?
charTop += 5;
//If the character's bottom is hitting the ground,
//Stop moving
if(charTop + charHeight > groundTop) {
charTop = groundTop - charHeight;
}
//Set the character's final position
character.style.top = charTop + "px";
},33);
#character {
position: absolute;
width: 40px;
height: 40px;
left: 50px;
background-color: #F00;
}
#ground {
position: absolute;
width: 300px;
height: 60px;
left: 0px;
background-color: #A66;
}
<div id="character"></div>
<div id="ground"></div>
One more thing: While there are convoluted ways to get element positions when elements use different positioning properties (ex: the player uses top/left coordinates, where the ground uses bottom), it's a lot harder to manage.
The only jQuery that was being used in that linked answer was to get with width,height, and position of the divs, which are somewhat trivial to retrieve using pure JS:
CSS / JavaScript - How do you get the rendered height of an element?
jquery position() in plain javascript
How do I retrieve an HTML element's actual width and height?
It's not returning anything because the .top .left and height variables in the return statement were relying on jQuery functions that retrieve the information mentioned above.

create a div that would grow as if it is a bubble

I have a circular background image inside a div. to start off with i need to not have the 'bubbles' to display. and after arriving on that page the bubble would grow into place like a bubble or in other words 'pop' into place. I have no idea how i would go about creating this in jquery. this also needs to work on all browsers including ie7+ any help would be grateful
jQuery show() function
jQuery animate
These should give you an idea.
You might also consider using images to illustrate what you're trying to achieve.
I recommend building the content you need, and then asking people how you can change it to get the results you want. That will be easier for people to answer.
For the popping effect you really need to animate 4 different styles, depending on your CSS preference you can animate top and left or if you're using margins (why?) margin-top and margin-left, this will give you the effect of the "bubble" expanding center outwards instead of top left to bottom right.
This is a jQuery example for top/left
var newHeight = 300;
var newWidth = 300;
jQuery('#element').animate({
"top":newHeight/2,
"left":newWidth/2,
"height":newHeight,
"width":newWidth,
"opacity":1
}, 'fast', easeInOutCirc);
You may find the easing effects here: http://gsgd.co.uk/sandbox/jquery/easing/
its worth noting you should be a little more specific with your questions, we're not mind readers :)
This is a simplified version of this fiddle where I did something very similar to what you're doing. Hope it helps.
function(){
var position = $('#bubbleposition'),
bubble = $('#bubble'),
startRadius = 200,
newRadius = 400,
startleft = 10,
starttop = 10,
endleft = 50,
endtop = 50;
position.css({left: startleft, top: starttop, 10)});
bubble.css({height: startRadius, width: startRadius});
position.animate({left: endleft, top: endtop});
bubble.animate({height: newRadius, width: newRadius}, 400);
}
<div id='bubbleposition'>
<div id='bubble'>
Hello!
</div>
</div>

jquery javascript resize jitter

I have some simple javascript that I'm using to auto-adjust the width of elements on pages and to vertically center the text on these pages.
My script works, but in IE9 and a little in Safari there is a distinct moment where the elements are not resized and they jump across the page. It's just a momentary flash, but it bugs me as I'm generally not a "good enough" kind of person. Here is my own script:
$(document).ready(function() {
var containerwidth = $("#main_content").css("width");
var picwidth = $(".picture").css("width");
$(".picture").parent().css("width", picwidth);
var correctwidth = parseInt(containerwidth) - parseInt(picwidth);
$(".main-text").css("width",correctwidth-25);
if( $(".margins").css("width") ) {
$(".title").css("width", parseInt($(".width-set").css("width"))+10);
} else {
$(".title").css("width", parseInt($(".title").parent().css("width"))-10);
}
var container_height = $(".main-text").height();
var text_height = $(".vert-align").height();
var offset = (container_height - text_height) / 2;
$(".vert-align").css("margin-top", offset);
[...]
});
I realize the use of explicit offsets and whatnot is hackish, but I'm in a hurry and will correct it later. And yes, I am using jQuery.
This is stored in a file, and I've tried both calling it in the head, and also directly after the elements it affects, but the result is the same. Is this jitter just a fact of life for using element manipulation with javascript, or is there some solution I've missed on the forums?
Thanks!
I suspect the reason is because you are calling this in the $(document).ready(), which runs after the DOM is loaded (i.e. your elements are already displayed).
If you absolutely have to resize elements after they've loaded, the only thing I can think of that might help is having an overlay that covers the entire window, maybe something like:
#overlay{
position: fixed;
width: 100%; height: 100%;
background: #fff;
z-index: 9001;
}
And then hiding the overlay via $("#overlay").hide() after the resizing in your $(document).ready() function. I haven't tested this so I don't know if it works. You might have to add a short setTimeOut as well.
To be honest, though, this solution feels very dirty. Hopefully someone else can think of something more elegant.
#ZDYN is correct. The "flicker" happens when the page is displayed but the jQuery code has not been executed.
You can try to set in the css your elements to "visibility: hidden" so they will have their dimensions for the calculations, then change the visibility to "visible" after the resizing.

jQuery and margin: 0 auto

So, this is a problem that's been asked before, but I'm hoping we can lay it to rest: I'm using jQuery 1.4. If I define the style
#obj { margin: 0 auto; }
and then do
$('#obj').css('marginLeft');
the result is the computed value in pixels. Is there any way to tell whether those pixels come from the auto calculation or not, without parsing document.styleSheets?
This solution would also be triggered if the margins were set to percentages, but it might be good enough for your purposes. Basically, you record which margins change on resize. So you'd record the margins before resize to an array:
var aMargins = [];
$('.yourObjs').each(function(i,obj){
var objML = $(obj).css('marginLeft');
aMargins.push(objML);
});
Then resize the window, see which margins changed (these will be either 'auto' or %), do what you need to do to them and return he window to original size:
var wW = $(window).width();
var wH = $(window).height();
window.resizeTo(wW - 5, wH);
$('.yourObjs').each(function(i,obj){
if ($(obj).css('marginLeft') != aMargins[i]) {
// your centering code here
}
}
window.resizeTo(wW,wH);
If your centering code just adjusts the left margin then this should work fine for % based margins too. I can't test this code or provide an example because I'm on the road and writing from my phone, but hopefully this works or helps you come up with something that will.
You can't get the auto from the element itself, because styles are cascading, what if you had this?
#obj { margin: 0 auto; }
div #obj { margin: 0 10px; }
Which is it? Depends on the page and how it cascades, the basic concept is you're getting the calculated style properties on that element, what's in the stylesheet doesn't matter, there could be 20 stylesheets, etc.
Basically it boils down to this: getting auto vs 000px is a really rare request and would required a lot of extra code to figure out, so much so that it's an easy case of "no, this doesn't belong in core". However, there are plugins to do CSS parsing.
Short answer: jQuery core cannot (doesn't have code to) do this, jQuery with plugins, or just JavaScript in general yes you can.

Categories