So I have these DIVs which I have arranged to slide left an right inside of the parent.
See the following JSFiddle to see the design:
http://jsfiddle.net/StevP/C9WL7/
You can see that by adjusting the margin-left of the first child DIV by multiples of -100%, it's rather simple to correctly horizontally position the DIVs inside the parent. Therefore, it's very easy to animate.
Now, this brings me to my issue. I'm using jQuery to move them left and right. It works great. However, I'd like to choose which child the parent gets its height from.
I know, I can just add...
$('#parent').height($('.child:eq()').outerHeight());
...Which is what I have it currently doing. However, the contents of the children are likely to change causing them to resize (by animate) and, therefore, be cut off. So, having a set height isn't a possibility.
I need to use height:auto; on the parent and somehow cause it to ignore the heights of specific children. I can't for the life of me think of a way.
I don't want to use a timer and onresize/.resize() don't seem to work with my Chrome.
You could use jQuery to monitor the DOM subtree and adjust the height of your parent div in the callback like this:
$('.content').bind('DOMSubtreeModified', function(e) {
if (e.target.innerHTML.length > 0) {
$(".parent").height($(".content").height());
}
});
Here's a working jsfiddle: http://jsfiddle.net/9386d/
And a question explaining the dom subtree: jQuery watch for domElement changes?
jQuery docs for bind(): http://api.jquery.com/bind/
Well... To be perfectly honest I'm not really a huge fan of jQuery anymore so I feel bad offering this answer. It just feels so frik'n inefficient, but here is a solution that does three things: 1) it resizes the hight of the container on step and uses a CSS transition attribute for eye candy (works just as well without). 2) it sets the child height of all but the current child to 0 and uses overflow:hidden so they don't affect the flow of the document anymore. 3) it resets these children to automatic height on animation start so they are visible during transition. All I can say is "yuck", but it does work.
CSS
.child{
...
overflow:hidden;
}
jQuery
var animation_prefs = {
duration: 3000,
start: function() {
$('.child').height('auto');
},
step: function(now) {
var current_index = (Math.floor((now + 50) / 100) * -1);
$('#parent').height($('.child:eq(' + current_index + ')').outerHeight());
$('#parent').data('current', current_index);
},
complete: function() {
$('#parent').height('auto');
$('.child:not(:eq('+$('#parent').data('current')+'))').height(0);
}
}
$('.child:eq(0)').animate(
{
marginLeft:'-200%' //~ Move it back 2 children
},
animation_prefs
).animate(
{
marginLeft:'-100%' //~ Move it back 1 child
},
animation_prefs
).animate(
{
marginLeft:'-200%' //~ Move it back 2 children again
},
animation_prefs
);
Demo
http://jsfiddle.net/Gq4xs/show
Source
http://jsfiddle.net/Gq4xs/
Related
I need to know if the end of a div element is currently visible in the users' browser.
I tried something I saw on the web, but scrollTop() always gave me zero in my Browser. I read something about an issue in Chrome, but I didn't understand quite well.
jQuery(
function($) {
$('#flux').bind('scroll', function() {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
alert('end reached');
}
})
}
);
My idea is the following:
1- User loads page and sees a Bar (sticky div at bottom visible page) with some information.
2- After scrolling a bit, and reaching the end of a div element, this bar will position there, after the div. This is the bar's original position
I wasn't really able to know when I was at the end of the div element. Eventually I found this code:
if ($(window).scrollTop() >= $('#block-homepagegrid').offset().top + $('#block-homepagegrid').outerHeight() - window.innerHeight) {
$('.hero-special-message').removeClass('hero-special-messege-scrolling');
} else {
$('.hero-special-message').addClass('hero-special-messege-scrolling');
}
});
I see that it's working, but I'm having a bit of trouble understanding what it does.
I know the following:
1. $(window).scrollTop();
this gives me the amount of pixels the user has scrolled, pretty self explanatory.
2. $('#block-homepagegrid').offset().top;
I THINK this is the distance between the start of the page and the start of the div. I know it's the current coordinates, but what is top exactly here?
3. $('#block-homepagegrid').outerHeight();
this gives the height of the element, I know there are 3, like
height(), innerHeight() and outerHeight(), if you want to take into
account border, margin, padding, which is the better to use?
4. window.innerHeight;
I understand this is what the user sees, but I'm having troubles understanding why does it matter for my situation.
Thanks!
You may be interested in the native JavaScript IntersectionObserver API. It automatically figures out what percentage of a given element is visible in the window and triggers callbacks based on that. So then you can do this:
function visibleHandler(entries) {
if (entries[0].intersectionRatio >= 1.0) {
// The whole element is visible!
} else {
// Part of it is scrolled offscreen!
}
}
const observer = new IntersectionObserver(visibleHandler, {threshold: 1.0});
observer.observe(document.getElementById('flux'));
Now, whenever the element with ID flux is 100% in view, it will trigger the visibleHandler. It will also trigger again if it's scrolled back out of view; that's why the function checks the ratio of visibility to see if it just hit 100% or just got reduced from 100%. You could be more fancy and use the observer entry's insersectionRect, which gives you the rectangle containing the visible portion of the element, and use that to determine top/bottom visibility.
I am just trying to get the mouse hover div's position at the right according to the space around. Somehow I am able to do this in first two columns but not for other columns. May be my calculations while writing the condition state are wrong.
Can anyone please help?
JS Fiddle URL:
http://jsfiddle.net/mufeedahmad/2u1zr11f/7/
JS Code:
$('.thumb-over-team li').find('.cover').css({opacity:0});
$('.thumb-over-team li').on('mouseenter', function(){
var $this = $(this),
thisoffset = $this.position().left,
openDivId = $(this).find('.cover'),
thumbContainer = '.thumb-over-team',
speedanim = 200;
if(thisoffset + openDivId.outerWidth() >= $(thumbContainer).outerWidth()){
//thisoffset = $(thumbContainer).outerWidth() - openDivId.outerWidth() - 212;
thisoffset = thisoffset - openDivId.outerWidth()+10;
openDivId.stop().css({'z-index':'9999'}).animate({'opacity':'1', 'left':-thisoffset}, 200);
}else{
openDivId.stop().css({'z-index':'9999'}).animate({'opacity':'1', 'left':'212px'}, 200);
}
}).on('mouseleave', function(){
$(this).find('.cover').stop().css({'z-index':'-1'}).animate({'opacity':'0', 'left':'200px'}, 200);
});
$('.close-parent').on('click', function(){
$(this).parents('.cover').stop().css({'z-index':'-1'}).animate({'opacity':'0', 'left':'200px'}, 200);
});;
In your first conditional, try to calculate the position of the offset as:
thisoffset = ($(thumbContainer).outerWidth() - openDivId.outerWidth() - thisoffset);
That way, you're adjusting the appearing square (.cover) when it doesn't fit inside the container, to be as close possible to its rightmost edge: (maximum width - appearing square width - current li position)
Calculated this way, you can animate it with the new offset in positive:
openDivId.stop().css({'z-index':'9999'}).animate({'opacity':'1', 'left':thisoffset}, 200);
See it working here.
For elements that "almost" fit, the current system isn't completely precise because of what I already pointed out in my previous comment: the appearing square, even if it were at 0 opacity, would still be inside the containing element (($(thumbContainer)) or .thumb-over-team) and it would add its width to the total width of the container.
So your conditional may think that there's enough available space in the container to make the expandable element fit, but that would go out of the screen. As an example, notice that there's a horizontal scrollbar from the very beginning, caused by this effect, where your containing .thumb-over-team element doesn't fit in the screen.
But I would say that more precision in this point would require a fresh new approach to your system where the appearing .cover elements were out of the containing ul .thumb-over-team
Fresh take on the problem, essentially based on the main issue: the expandable text block (.cover) used to add its width to the container (.thumb-over-team). This altered the calculations on available container space, and made the text containers go off screen.
The solution is to make sure the expandable .cover elements aren't contained inside the .thumb-over-team element, so they won't impact the calculations on available width.
Here is a JSFiddle containing this new approach: link.
Explanation of how it works:
The idea was to create a separate element called .cover-container and let's put all the expandable .cover elements in there.
We want to associate every image in the li elements in .thumb-over-team with their appropriate .cover (so the first image triggers the first .cover to show, the second image would show the second cover, and so on.) We achieve is by finding out the index of the element that triggered the event:
thisLiIndex = $this.index() + 1
And then selecting the cover in the matching position:
openDivId = $('.cover-container .cover:nth-child(' + thisLiIndex + ')')
The expandable covers shouldn't interfere with the mouseenter or mouseleave events of .thumb-over-team, so we make it to ignore mouse events via CSS:
.cover-container{pointer-events:none;}
Changing from one image to another would automatically trigger new events, so the expanding covers stay visible when the mouse stays on the images, but close automatically when the mouse exits them.
Since the covers are now outside of $(thumbContainer), openDivID.outerWidth() does not alter $(thumbContainer).outerWidth(), and we can use that safely in our positioning.
If I understand the placement that you want, for covers that fit, the position is the current offset (position of the li element that triggered the event) plus the width of the image and some subtle margin
imageWidth + rightSeparation + thisoffset
And for covers that won't fit inside of the screen, we keep them just inside of the screen
thisoffset = $(thumbContainer).outerWidth() - openDivId.outerWidth();
I've run into a bit of trouble with a project.
I have a menu item, when it is clicked I would like a loading animation that will wipe left-to-right and change the colour of both the text and the background.
The best way I could think to do this is to duplicate the div, apply a 'cloned' class that changes the colours and lays it atop the clicked div. I can't seem to make a wipe work though.
I'm trying to use clip:
$('.flight').click(function () {
$(this).clone(true).addClass('cloned').appendTo($(this).parent())
$(this).siblings('.cloned').stop().animate({
'clip': 'rect(0px 0px 300px 0px)'
}, 1000)
});
JSFIDDLE
Any advice on where I'm going wrong would be really appreciated!
Ok so I found a work-around from the clip issue. It's not pretty but it works! I'm only allowing myself to use this as the animation is not required for functionality, and the cloned block is to be deleted upon completion.
$('.flight').click(function() {
// Clone and add the class
$(this).clone(true).addClass('cloned').appendTo($(this).parent())
// For every div under .cloned fix the width and height, this will prevent
// any responsiveness that we don't want.
jQuery.each($('.cloned div'), function(){
$(this).css('width', $(this).innerWidth())
$(this).css('max-height', $(this).innerHeight())
})
// Set the container width to 0 now, would not work before as we need
// calculable widths. Then animate!
$('.cloned').css('width', '0')
$('.cloned').animate({
width: '100%'
})
});
JSFIDDLE
I have I div or some other element which I load content into with:
$('#my_div').load('ajax.php',function(){
//Do random stuff.
}
However the height of the div will then change, causing the page to jump up and down, looking ugly.
Is there a way for it to animate the height when the new content is loaded or changed? I know one can do this with FluidMoveBehavior in C#.
How can I achieve the same effect with Javascript/jQuery?
Here's some Fiddle
When you want to create a height or width animation with jQuery you have to set a number indicating the desired size. I assume that you use height: auto in this case so you have to find a little workarround.
Get the height:
var autoHeight = $("#content").height("auto").height();
Animate to autoHeight:
$("#content").animate({height: autoHeight}, 1000);
And together:
var currentHeight = $("#content").height();
var autoHeight = $("#content").height("auto").height();
$("#content").height(currentHeight);
$("#content").animate({height: autoHeight}, 1000);
Stolen from here
What I do is the opposite. I animate the page to scroll to the top if not already BEFORE I call the load.
So that the top of any new dynamic content is always in view.
I know this isn't the answer you were looking for, but I've found it works best.
You could hide #my_div before the load(), and then slideDown() in the complete function:
$('#my_div').hide().load('ajax.php', function() {
$(this).slideDown();
});
Or, create a temporary element, hide it, append it, use its height to animate #my_div once the load is complete, and then remove it.
$('<span/>').hide().appendTo('body').load('ajax.php', function(text) {
$('#my_div').animate({ height: $(this).height() }, '800').html(text);
$(this).remove();
});
I am using jQuery animate to change the position of multiple elements on the page (decorative elements). I want the element to be deleted if it exits body area. (if left is larger than body width or top is larger than body height).
The following can not be used in my case:
overflow hidden for the body
manually animating the element. I want to use jQuery animate to keep it simple (I dinamically create elements, animate them then I don't care about them, don't keep track of them, they have a .remove() methode when the animation is complete)
http://jsfiddle.net/a7Nck/
So in this JSfiddle I want the red div to dissappear when it reaches right edge of the body so that no scrollbars will appear.
Isn't there any CSS3 media query for example so that if a div is not in the viewport it will be hidden?
EDIT:
I just thought of a solution: get the width of the body prior to triggering the animation and then animate the top and left by using the minimum between the body size and what the animation should do. The problem is that this will affect animation speed.
You can use animate's step function.
The second version of .animate() provides a step option — a callback function that is fired at each step of the animation. This function is useful for enabling custom animation types or altering the animation as it is occurring. It accepts two arguments (now and fx), and this is set to the DOM element being animated.
var w = $(window).width()
$('div').animate({
left: '20px'
}, 500).delay(1000).animate({
left: '2000px'
}, {
step: function(now, fx) {
if (now > w) {
$(fx.elem).remove()
}
}
}, 1000);
Fiddle
One possible workaround (assuming your first restriction is about globally adding overflow: hidden on your CSS): add overflow: hidden with js when the animation starts, and remove it when it ends:
$('body').css('overflow', 'hidden');
$('div').animate({left: '20px'},400).delay(1000).animate(
{left: '2000px'},1000, false, function(){
$(this).hide();
$('body').css('overflow', 'auto');
});
http://jsfiddle.net/a7Nck/3/
Just hide the div when the last animation get completed i.e.
$('div').animate({left: '20px'},400).delay(1000).animate({left: '2000px'},1000, function(){ $(this).hide(); });
See DEMO
As soon as the div leaves the visible area, the scrollbar will appear. If you want to prevent the scrollbar from appearing, you can't allow the div to leave the screen. Here's my solution:
$('div')
.animate({left: '20px'},400)
.delay(1000)
.animate(
{left: ($(window).width()-$('div').width()) + "px"},
1000,
null, // default easing
function() { $('div').hide() }
);
Jsfiddle: http://jsfiddle.net/j4rdA/1/