javascript - position not being set properly on page load - javascript

I am creating a coverflow plugin but I have a slight problem when it first loads.
The size/styles of the images is set based on their position in the coverflow. When the page first loads the images all resize properly but they do not reposition themselves. If I them use the left and right navigation they work correctly.
I am not sure what is causing this. I thought it might be something to do with the variable that sets the starting position of the coverflow...
Here's my code:
<script type="text/javascript" src="/scripts/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var coverflowPos = Math.round($('#coverflow img').length / 2)
$('#coverflow img').each( function(i) {
$(this).css({'opacity' : 1-(Math.abs(coverflowPos-i)*0.4), 'z-index' : 100-(Math.abs(coverflowPos-i)) }).width(200-(Math.abs(coverflowPos-i)*50)).height(128-(Math.abs(coverflowPos-i)*50));
});
// If I run the testme() function here, it animates to the right place but I want it to start in this position rather than animate to it
$('#moveLeft').click( function() {
if(coverflowPos > 1) {
coverflowPos = coverflowPos-1
}
testme();
});
$('#moveRight').click( function() {
if(coverflowPos < $("#coverflow img").length -1) {
coverflowPos = coverflowPos+1
}
testme();
});
function testme() {
$('#coverflow img').each( function(i) {
$(this).animate({
opacity: 1-(Math.abs(coverflowPos-i)*0.4),
width: 200-(Math.abs(coverflowPos-i)*50),
height: 128-(Math.abs(coverflowPos-i)*50)
}, {
duration: 500,
easing: 'easeInOutSine'
}).css({ 'z-index' : 100-(Math.abs(coverflowPos-i)) });
});
};
});
</script>
And here's a link to a jsfiddle:
http://jsfiddle.net/r8NqP/4/

Calling testme() at the end of the ready() function moves them into place. It does ease them in though, which looks a bit odd, could get rid of the ease in testme() by adding a doease parameter.

Check you fist each :
'z-index' : 100-(Math.abs(coverflowPos-i)) }).width(200-(Math.abs(coverflowPos-i)*50)).height(128-(Math.abs(coverflowPos-i)*50));
I think U mean:
'z-index' : 100-(Math.abs(coverflowPos-i)),
'width' : 200-(Math.abs(coverflowPos-i)*50),
'height': 128-(Math.abs(coverflowPos-i)*50)
Linke In your testme() function ?!
After that, you can also add a "Hack", by executing testme(true); at the end of script.
And add, in your testme() function , a test parameter to set the duration at 0 or simply disable animate and replace by CSS().
But, it just a Hack.

200-(Math.abs(coverflowPos-i)*50) may be less than 0 -- e.g.,
200-(5-0)* 50= 200 - 250 = -50
And the negative width ends up not being applied, leaving the width at its original 200px value. The opacity gets set properly, so all you get is a huge blank space where the image is.
var width = 200-(Math.abs(coverflowPos-i)*50);
if ( width < 0 ) width = 0;
covers the init nicely.
I haven't bothered to check why it's okay once it's animated -- my guess is, that the images were already small, so it's not as noticeable.

The problem came from "Each index", that not correctly used to compute the Width and Height of the first image.
Try this :
$('#coverflow img').each( function(i) {
i++;
$(this).css({...
And remove the Blank.gif...
Here, you find my fork fiddle : http://jsfiddle.net/akarun/FQWQa/

Related

Using a jquery slider for text instead of images?

This may be a little too specific, but I have a jquery slider that I am using <p> classes instead of images to cycle through customer quotes. Basically the problem I am running into right now is when it is static and non moving (JS code is commeneted out) they are aligned how I want them to be. As soon as the JS is un commented, they stretch out of view and you just see a white box?
Any ideas?
How I want each panel to look like:
jsfiddle
So I sort of made this my Friday project. I've changed a whole lot of your code, and added a vertical-align to the quotes and authors.
Here's the fiddle http://jsfiddle.net/qLca2fz4/49/
I added a whole lot of variables to the top of the script so you could less typing throughout.
$(document).ready(function () {
//rotation speed and timer
var speed = 5000;
var run = setInterval(rotate, speed);
var slides = $('.slide');
var container = $('#slides ul');
var elm = container.find(':first-child').prop("tagName");
var item_width = container.width();
var previous = 'prev'; //id of previous button
var next = 'next'; //id of next button
Since you used a % based width I'm setting the pixel widths of the elements in case the screen is reszed
slides.width(item_width); //set the slides to the correct pixel width
container.parent().width(item_width);
container.width(slides.length * item_width); //set the slides container to the correct total width
As you had, I'm rearranging the slides in the event the back button is pressed
container.find(elm + ':first').before(container.find(elm + ':last'));
resetSlides();
I combined the prev and next click events into a single function. It checks for the ID of the element targeted in the click event, then runs the proper previous or next functions. If you reset the setInterval after the click event your browser has trouble stopping it on hover.
//if user clicked on prev button
$('#buttons a').click(function (e) {
//slide the item
if (container.is(':animated')) {
return false;
}
if (e.target.id == previous) {
container.stop().animate({
'left': 0
}, 1500, function () {
container.find(elm + ':first').before(container.find(elm + ':last'));
resetSlides();
});
}
if (e.target.id == next) {
container.stop().animate({
'left': item_width * -2
}, 1500, function () {
container.find(elm + ':last').after(container.find(elm + ':first'));
resetSlides();
});
}
//cancel the link behavior
return false;
});
I've found mouseenter and mouseleave to be a little more reliable than hover.
//if mouse hover, pause the auto rotation, otherwise rotate it
container.parent().mouseenter(function () {
clearInterval(run);
}).mouseleave(function () {
run = setInterval(rotate, speed);
});
I broke this in to its own function because it gets called in a number of different places.
function resetSlides() {
//and adjust the container so current is in the frame
container.css({
'left': -1 * item_width
});
}
});
//a simple function to click next link
//a timer will call this function, and the rotation will begin :)
And here's your rotation timer.
function rotate() {
$('#next').click();
}
It took me a little bit, but I think I figured out a few things.
http://jsfiddle.net/qLca2fz4/28/
First off, your console was throwing a few errors: first, that rotate wasn't defined and that an arrow gif didn't exist. Arrow gif was probably something you have stored locally, but I changed the 'rotate' error by changing the strings in the code here to your actual variables.
So, from:
run = setInterval('rotate()', speed);
We get:
run = setInterval(rotate, speed);
(No () based on the examples here: http://www.w3schools.com/jsref/met_win_setinterval.asp)
But I think a more important question is why your text wasn't showing up at all. It's because of the logic found here:
$('#slides ul').css({'left' : left_value});
You even say that this is setting the default placement for the code. But it isn't..."left_vaule" is the amount that you've calculated to push left during a slide. So if you inspect the element, you can see how the whole UL is basically shifted one slide's worth too far left, unable to be seen. So we get rid of 'left_value', and replace it with 0.
$('#slides ul').css({'left' : 0});
Now, there's nothing really handling how the pictures slide in, so that part's still rough, but this should be enough to start on.
Let me know if I misunderstood anything, or if you have any questions.
So, a few things:
1) I believe you are trying to get all of the lis to be side-by-side, not arranged up and down. There are a few ways to do this. I'd just make the ul have a width of 300%, and then make the lis each take up a third of that:
#slides ul {
....
width: 300%;
}
#slides li {
width: calc(100% / 3);
height:250px;
float:left;
}
2) You got this right, but JSFiddle automatically wraps all your JS inside a $(document).ready() handler, and your function, rotate needs to be outside, in the normal DOM. Just change that JSFiddle setting from 'onload' to 'no wrap - in head'
3) Grabbing the CSS value of an element doesn't always work, especially when you're dealing with animating elements. You already know the width of the li elements with your item_width variable. I'd just use that and change your code:
var left_indent = parseInt($('#slides ul').css('left')) - item_width;
$('#slides ul').animate({'left' : left_indent}, 1500, function () {
to:
$('#slides ul').stop().animate({'left' : -item_width * 2}, 1500, function () {
4) Throw in the .stop() as seen in the above line. This prevents your animations from overlapping. An alternative, and perhaps cleaner way to do this, would be to simply return false at the beginning of your 'next' and 'prev' functions if #slides ul is being animated, like so:
if ($('#slides ul').is(':animated')) return false;
And I think that's everything. Here's the JSFiddle. Cheers!
EDIT:
Oh, and you may also want to clearInterval at the beginning of the next and prev functions and then reset it in the animation callback functions:
$('#prev').click(function() {
if ($('#slides ul').is(':animated')) return false;
clearInterval(run);
$('#slides ul').stop().animate({'left' : 0}, 1500,function(){
....
run = setInterval('rotate()', speed);
});
});

Slide boxes with margin-left check if overslided

I made a simple content/box slider which uses the following javascript:
$('#left').click(function () {
$('#videos').animate({
marginLeft: '-=800px'
}, 500);
});
$('#right').click(function () {
$('#videos').animate({
marginLeft: '+=800px'
}, 500);
});
Here is the demo: http://jsfiddle.net/tjset/2/
What I want to do and I can't figure out how to show and hide arrows(left and right box) as the all the boxes slided.
So I clicked 4 time to the LEFT and slided all the boxes! then hide "left" so that you can't give more -800px
What can I do?
What you can do is check after the animation completes to see if the margin-left property is smaller or larger than the bounds of the video <div>. If it is, depending on which navigation button was clicked, hide the appropriate navigation link.
Check out the code below:
$('#left').click(function () {
// reset the #right navigation button to show
$('#right').show();
$('#videos').animate({
marginLeft: '-=800px'
}, 500, 'linear', function(){
// grab the margin-left property
var mLeft = parseInt($('#videos').css('marginLeft'));
// store the width of the #video div
// invert the number since the margin left is a negative value
var videoWidth = $('#videos').width() * -1;
// if the left margin that is set is less than the videoWidth var,
// hide the #left navigation. Otherwise, keep it shown
if(mLeft < videoWidth){
$('#left').hide();
} else {
$('#left').show();
}
});
});
// do similar things if the right button is clicked
$('#right').click(function () {
$('#left').show();
$('#videos').animate({
marginLeft: '+=800px'
}, 500, 'linear', function(){
var mRight = parseInt($('#videos').css('marginLeft'));
if(mRight > 100){
$('#right').hide();
} else {
$('#right').show();
}
});
});
Check out the jsfiddle:
http://jsfiddle.net/dnVYW/1/
There are many jQuery plugins for this. First determine how many results there are, then determine how many you want visible, then use another variable to keep track with how many are hidden to the left and how many are hidden to the right. So...
var total = TOTAL_RESULTS;
var leftScrolled = 0;
var rightScrolled = total - 3; // minus 3, since you want 3 displayed at a time.
instead of using marginLeft I would wrap all of these inside of a wrapper and set the positions to absolute. Then animate using "left" property or "right". There's a lot of code required to do this, well not MUCH, but since there are many plugins, I think you'd be better off searching jquery.com for a plugin and look for examples on how to do this. marginLeft is just not the way to go, since it can cause many viewing problems depending on what version of browser you are using.

moving boxes plugin callback function

this kind of emergency, so please, can someone help me...
I'm using movingboxes plugin for slideshow(this is the original plugin:http://css-tricks.com/moving-boxes/)
I need help with setting callback function add to the end of animation. I need to add fading effect, when currentSlidecomplete sliding,it should start fading into another view of the same image, for example,surrentSlide src is images/dr1.jpg and i need it to fade to images/dr1b.jpg and come back to images/dr1.jpg. looping through each current Slide
something like
completed :
function(e, slider, tar){
//fading for each currentSlide goes here;//
}
Something like you describe is already in the documentation
see the documentation here [1] and more specifically here [2].
EDIT: check jsfiddle here, i used a jquery add-on http://jsfiddle.net/r6yWC/157/
the add-on is here http://jqueryfordesigners.com/image-cross-fade-transition/
I also edited the code section below. I added the class "fade" to the img tag like this:
<img class="fade" src="http://chriscoyier.github.com/MovingBoxes/demo/4.jpg" alt="picture" style="background: url(http://chriscoyier.github.com/MovingBoxes/demo/2.jpg);"/>
In the 2nd link you will find a movingBoxes sample with a completed callback.
(function ($) {
$.fn.cross = function (options) {
return this.each(function (i) {
// cache the copy of jQuery(this) - the start image
var $$ = $(this);
// get the target from the backgroundImage + regexp
var target = $$.css('backgroundImage').replace(/^url|[\(\)'"]/g, '');
// nice long chain: wrap img element in span
$$.wrap('<span style="position: relative;"></span>')
// change selector to parent - i.e. newly created span
.parent()
// prepend a new image inside the span
.prepend('<img>')
// change the selector to the newly created image
.find(':first-child')
// set the image to the target
.attr('src', target);
// the CSS styling of the start image needs to be handled
// differently for different browsers
if ($.browser.msie || $.browser.mozilla) {
$$.css({
'position' : 'absolute',
'left' : 0,
'background' : '',
'top' : this.offsetTop
});
} else if ($.browser.opera && $.browser.version < 9.5) {
// Browser sniffing is bad - however opera < 9.5 has a render bug
// so this is required to get around it we can't apply the 'top' : 0
// separately because Mozilla strips the style set originally somehow...
$$.css({
'position' : 'absolute',
'left' : 0,
'background' : '',
'top' : "0"
});
} else { // Safari
$$.css({
'position' : 'absolute',
'left' : 0,
'background' : ''
});
}
// similar effect as single image technique, except using .animate
// which will handle the fading up from the right opacity for us
$$.hover(function () {
$$.stop().animate({
opacity: 0
}, 250);
}, function () {
$$.stop().animate({
opacity: 1
}, 250);
});
});
};
})(jQuery);
$('#slider').movingBoxes({
// **** Appearance ****
// start with this panel
...
...
//-----> here is your callback
// callback after animation completes
completed: function(e, slider, tar){
var img = slider.$panels.eq(tar).find('img');
img.cross();
img.stop().animate({opacity: 0}, 1250).delay(500).animate({opacity: 1}, 2550);
}
});​
[1] https://github.com/chriscoyier/MovingBoxes/wiki
[2] http://jsfiddle.net/Mottie/r6yWC/2/

jquery animation and .offset

Basically I have an image that is 780px long and I have a window through which you can only see 390px at a time. There are left and right arrows so you can scroll one way and then the other. I would like the arrows to be disabled once you reach the end of the image either at 0px or -780px. I have tried the following code just to see if I am going in the right direction however it only works with the ">" sign and I need it to work with "==":
$(function() {
$(".big-fwd img").click(function() {
var offset = $(".wrap-nga").offset();
$(".wrap-nga").animate({
left: "-=390px"
})
if (offset > "-780px") {
alert("hello");
}
});
The second problem is that when I write the code I really want to have instead of the alert, nothing at all happens:
$(function() {
$(".big-fwd img").click(function() {
var offset = $(".wrap-nga").offset();
$(".wrap-nga").animate({
left: "-=390px"
})
if (offset > "-780px") {
$(".big-fwd img").removeAttr();
}
});
I'm really at a loss. I've tried "position" instead of "offset" but that's not the problem.
Any help would be fantastic. You can also get a better idea of what I'm trying to do by going to http://www.lieslswogger.com and clicking on one of the images in the gallery. Thank you!!
I think your comparison issue is due to the fact the the result of $.offset() is an object, not a value.
From http://api.jquery.com/offset/
.offset() returns an object containing the properties top and left.
You probably want to use offset.left, in your case.
Hope that helps!
Do the offset check before animating. You also will need to compare a numeric value for the inequalities in this case.
$(".big-fwd img").click(function(){
var offset = $(".wrap-nga").offset();
if(offset.left < 780)
$(".wrap-nga").animate({ left: "-=390px" })
});
Similarly on back .big-back img:
if(offset.left > 0) // proceed with animation
Make sure you close your function. It should be:
$(function() {
$(".big-fwd img").click(function() {
var offset = $(".wrap-nga").offset();
$(".wrap-nga").animate({
left: "-=390px"
}) if (offset > "-780px") {
$(".big-fwd img").removeAttr();
}
});
});

JQuery - animate moving DOM element to new parent?

I have an image tag inside of a table cell, that I'd love to move to another table cell, and have that movement animated.
The code looks something like this...
<td id="cell1"><img src="arrow.png" alt="Arrow"/></td>
<td id="cell2"></td>
I'd like to move "arrow.png" to "cell2", and have some kind of transition effect, preferably with JQuery.
Any ideas?
Thanks!
This is actually quite difficult because you have to remove and add it to the DOM but keep its position. I think you're looking for something like this. Basically we don't animate either the arrow in #cell1 or #cell2. We just create a new one in the body-tag and animate that. That way we don't have to worry about the table cell positions because we can position relative to the document.
var $old = $('#cell1 img');
//First we copy the arrow to the new table cell and get the offset to the document
var $new = $old.clone().appendTo('#cell2');
var newOffset = $new.offset();
//Get the old position relative to document
var oldOffset = $old.offset();
//we also clone old to the document for the animation
var $temp = $old.clone().appendTo('body');
//hide new and old and move $temp to position
//also big z-index, make sure to edit this to something that works with the page
$temp
.css('position', 'absolute')
.css('left', oldOffset.left)
.css('top', oldOffset.top)
.css('zIndex', 1000);
$new.hide();
$old.hide();
//animate the $temp to the position of the new img
$temp.animate( {'top': newOffset.top, 'left':newOffset.left}, 'slow', function(){
//callback function, we remove $old and $temp and show $new
$new.show();
$old.remove();
$temp.remove();
});
I think this should point you in the right direction.
#Pim Jager's answer is pretty good, however if you have object references to the original element they would break since the the original element was replaced with a clone
I came up with what I think is a slightly cleaner solution in that it only has a single clone that show up for animation then goes away, leaving the original in the new location.
function moveAnimate(element, newParent){
//Allow passing in either a jQuery object or selector
element = $(element);
newParent= $(newParent);
var oldOffset = element.offset();
element.appendTo(newParent);
var newOffset = element.offset();
var temp = element.clone().appendTo('body');
temp.css({
'position': 'absolute',
'left': oldOffset.left,
'top': oldOffset.top,
'z-index': 1000
});
element.hide();
temp.animate({'top': newOffset.top, 'left': newOffset.left}, 'slow', function(){
element.show();
temp.remove();
});
}
To use: moveAnimate('#ElementToMove', '#newContainer')
You'll need to do this in two steps: (1) animation (2) rehoming.
The animation you can take care of with .animate(), as #Ballsacian points out. The rehoming can be accomplished with .html() - for the example above,
var arrowMarkup = $('#cell1').html(); //grab the arrow
$('#cell1').html(""); //delete it from the first cell
$('#cell2').html(arrowMarkup); //add it to the second cell
Of course, you'll have to complicate that code to integrate the animation. And this way of doing it won't cause the selection (I'm assuming you're selecting a table row?) to activate rows between the old selection and the new one, as the arrow passes by them. That'd be even more complex to achieve.
I have extended one of the other answers a little further so that now you can pass an object as a third parameter which serves as a vehicle during the animation. For example, if you want to move some <li> from one <ul> to another, your <ul> likely has a certain class that gives the <li> its styling. So, it would really be handy to animate your <li> inside a temporary vehicle <ul> that provides for the same styling as either the source or the target <ul> of the animation:
//APPENDS AN ELEMENT IN AN ANIMATED FASHION
function animateAppendTo(el, where, float){
var pos0 = el.offset();
el.appendTo(where);
var pos1 = el.offset();
el.clone().appendTo(float ? float : 'body');
float.css({
'position': 'absolute',
'left': pos0.left,
'top': pos0.top,
'zIndex': 1000
});
el.hide();
float.animate(
{'top': pos1.top,'left': pos1.left},
'slow',
function(){
el.show();
float.remove();
});
}
I was trying #Davy8's function which is quite good, but I found it quite jarring when the moved element snapped off the page at the start then back in at the end. The other page elements suddenly shifting interrupted an otherwise smooth animation, but this likely would depend on your page layout.
So this is a modified version of #Davy8's function, which should also smoothly shrink and grow space between parents.
function moveAnimate(element, newParent,
slideAnimationSpeed/*=800*/, spacerAnimationSpeed/*=600*/)
{
//Allow passing in either a jQuery object or selector
element = $(element);
newParent= $(newParent);
slideAnimationSpeed=slideAnimationSpeed||800;
spacerAnimationSpeed=spacerAnimationSpeed||600;
var oldOffset = element.offset();
var tempOutgoing=element.clone().insertAfter(element);
tempOutgoing.hide(); //Don't take up space yet so 'newOffset' can be calculated correctly
element.appendTo(newParent);
var newOffset = element.offset();
var tempMover = element.clone().appendTo('body');
tempMover.css({
'position': 'absolute',
'left': oldOffset.left,
'top': oldOffset.top,
'z-index': 1000,
'margin':0 //Necessary for animation alignment if the source element had margin
});
element.hide();
element.show(spacerAnimationSpeed).css('visibility', 'hidden'); //Smoothly grow space at the target
tempMover.animate({'top': newOffset.top, 'left': newOffset.left}, slideAnimationSpeed, function(){
element.css('visibility', 'visible');
tempMover.remove();
});
tempOutgoing.show().css('visibility', 'hidden');
tempOutgoing.hide(spacerAnimationSpeed, function(){ tempOutgoing.remove() }); //smoothly shrink space at the source
}
If the animation doesn't have to be the thing moving, this question which uses fadeIn and fadeOut gives a simple, clean answer with no cloning and still conveys the motion quite well:
Re-ordering div positions with jQuery?
For anyone still viewing this, I found the provided examples didn't fit exactly what I wanted and they didn't account for margins, so here's my version:
jQuery.fn.extend({
moveElement : function (newParent, speed, after) {
var origEl = $(this);
var moveToEl = $(newParent);
var oldOffset = origEl.offset();
var temp = origEl.clone().appendTo('body');
temp.css({
'position' : 'absolute',
'left' : parseInt(oldOffset.left) - parseInt(origEl.css('margin-left')),
'margin' : origEl.css('margin'),
'top' : oldOffset.top,
'z-index' : 1000,
'height' : moveToEl.innerHeight(),
'width' : moveToEl.innerWidth()
});
var blankEl = $('<div></div>').css({
height : moveToEl.innerHeight(),
margin : moveToEl.css('margin'),
position : 'relative',
width : moveToEl.innerWidth()
});
if (after) {
origEl.insertAfter(moveToEl);
blankEl.insertAfter(newParent);
}
else {
origEl.insertBefore(moveToEl);
blankEl.insertBefore(newParent);
}
origEl.hide();
var newOffset = blankEl.offset();
temp.animate({
'top' : blankEl.offset().top - parseInt(moveToEl.css('margin-top')),
'left' : newOffset.left - parseInt(moveToEl.css('margin-left'))
}, speed, function () {
blankEl.remove();
origEl.show();
temp.remove();
});
}
});
Move an element before another: $('.elementToFind').moveElement('.targetElement', 1000);
Move an element after another: $('.elementToFind').moveElement('.targetElement', 1000, 'after');
JQuery http://docs.jquery.com/Downloading_jQuery
JQuery Effects http://docs.jquery.com/Effects/animate#paramsoptions
Example
$("#go1").click(function(){
$("#block1").animate( { width:"90%" }, { queue:false, duration:3000 } )
.animate( { fontSize:"24px" }, 1500 )
.animate( { borderRightWidth:"15px" }, 1500);
});

Categories

Resources