jquery calculate height and width and animate content behind it - javascript

animate content behind h1
if h1 is top of the image don't animate
Currently works fine but I need to calculate the width of the h1 tag as well in order to animate the image just outside the h1.
Basically if the image sits outside the width of the h1 should show.
I hope this is enough clear.
Demo.
js:
// Get the divs that should change
function displayThese() {
var $heading = $('h1');
var h1top = $heading.position().top;
var h1bottom = h1top + $heading.height();
var divs = $('li').filter(function () {
var $e = $(this);
var top = $e.position().top;
var bottom = top + $e.height();
return top > h1bottom || bottom < h1top;
});
return divs;
}
(function fadeInDiv() {
var divs = displayThese();
var elem = divs.eq(Math.floor(Math.random() * divs.length));
if (!elem.is(':visible')) {
elem.prev().remove();
elem.animate({
opacity: 1
}, Math.floor(Math.random() * 1000), fadeInDiv);
} else {
elem.animate({
opacity: (Math.random() * 1)
}, Math.floor(Math.random() * 1000), function () {
window.setTimeout(fadeInDiv);
});
}
})();
$(window).resize(function () {
// Get items that do not change
var divs = $('li').not(displayThese());
divs.css({
opacity: .3
});
});

You just have to use $.fn.width :
var $heading = $('h1');
var h1top = $heading.position().top;
var h1bottom = h1top + $heading.height();
var h1left = $heading.position().left;
var h1right = h1top + $heading.width();
var divs = $('li').filter(function () {
var $e = $(this);
var top = $e.position().top;
var bottom = top + $e.height();
var left = $e.position().left;
var right = left + $e.width();
return top > h1bottom || bottom < h1top || left > h1right || right < h1left;
});
return divs;
Here is a fiddle : http://jsfiddle.net/33Ec8/3/

Is this what you are looking for:
$(<element>).width()
$(<element>).height()
Demo here.

Related

extract a number from a property value

I am trying to create an animation, when a button is pressed, the div have to move to left 300 px by changing the left-margin,and stop.
I get the left margin value, but when I try to extract 300 px from it, it says that the var moveto is not a number, and current_left_margin`s value is 0px, how can I get this value to be a number, without the px?
here is my full code:
function get_vars() {
elem = document.getElementById('front-slide');
}
window.onload = get_vars;
function vb_anim() {
var interval = setInterval(anim, 10);
var elemstyle = window.getComputedStyle(elem);
var elemvidth = elemstyle.width;
var current_left_margin = elemstyle.getPropertyValue('margin-left');
var moveto = current_left_margin - 300;
console.log('current_left_margin= ' + current_left_margin );
console.log('moveto= ' + moveto );
var pos = 0;
function anim() {
if (pos == moveto) {
clearInterval(interval);
} else {
pos--;
elem.style.marginLeft = pos + 'px';
}
}
}
This should do:
var current_left_margin = parseInt(elemstyle.getPropertyValue('margin-left'));
If not, then:
var current_left_margin = parseInt(elemstyle.getPropertyValue('margin-left').replace('px', ''));

javascript, offsetTop, offsetBottom

I have a paragraph tag in my html id is move, I am trying to move the p tag to slowing fall down while on page load. but my code is not working.......
var speed = 12;
var direction = 1;
var getParagraph = document.getElementById("move");
getParagraph.onmouseover = moving;
function moving() {
var bo = getParagraph.offsetHeight;
var boTop = getParagraph.offsetTop;
var boBottom = boTop + bo;
// When right side of the box goes too far - change direction:
if (boBottom > document.body.offsetHeight) {
direction = -1;
}
// When left side of the box goes too far - change direction:
if (boTop < 0) {
direction = 1;
}
// Recalculate position:
getParagraph.style.Top = (boTop + speed * direction)
}
This is your code with minor changes, and it "works":
JS:
var speed = 12;
var direction = 1;
var getParagraph = document.getElementById("move");
document.getElementById("move").addEventListener("mouseover", moving);
//getParagraph.onmouseover = moving;
function moving() {
console.log("Moving??");
var bo = document.getElementById("move").offsetHeight;
var boTop = document.getElementById("move").offsetTop;
var boBottom = boTop + bo;
// When right side of the box goes too far - change direction:
if (boBottom > document.body.offsetHeight) {
direction = -1;
}
// When left side of the box goes too far - change direction:
if (boTop < 0) {
direction = 1;
}
// Recalculate position:
document.getElementById("move").style.marginTop = (boTop + speed * direction) + "px";
speed++;
}
CSS:
#move {
display : block ;
position : absolute ;
}
Hope it helps.

Jquery function should also work with other elements

I'm trying to make this function working multiple times:
Currently works only with the h1 tag
how can I make it working for the <div class="logo"> as well? I don't want to repeat the function, I need a way to make the function working for various elements.
demo: http://jsfiddle.net/33Ec8/4/
JS:
// Get the divs that should change
function displayThese() {
var $heading = $('h1');
var h1top = $heading.position().top;
var h1bottom = h1top + $heading.height();
var h1left = $heading.position().left;
var h1right = h1top + $heading.width();
var divs = $('li').filter(function () {
var $e = $(this);
var top = $e.position().top;
var bottom = top + $e.height();
var left = $e.position().left;
var right = left + $e.width();
return top > h1bottom || bottom < h1top || left > h1right || right < h1left;
});
return divs;
}
(function fadeInDiv() {
var divs = displayThese();
var elem = divs.eq(Math.floor(Math.random() * divs.length));
if (!elem.is(':visible')) {
elem.prev().remove();
elem.animate({
opacity: 1
}, Math.floor(Math.random() * 1000), fadeInDiv);
} else {
elem.animate({
opacity: (Math.random() * 1)
}, Math.floor(Math.random() * 1000), function () {
window.setTimeout(fadeInDiv);
});
}
})();
$(window).resize(function () {
// Get items that do not change
var divs = $('li').not(displayThese());
divs.css({
opacity: 0.3
});
});
Your question isn't stated very clearly, so I would strongly suggest describing what the code should do vs what it does.
That said, here is a half-blind attempt at answering what I think you want.
You could pass in the selector as a parameter to displayThese.
function displayThese(selectorString)
{
var $elementsUnderWhichNothingShouldFade = $(selectorString);
...
}
then when you call displayThese, you can pass in any complex selector you like.
var divsToChange = displayThese('h1, div.logo')
Of course, you would need to add extra logic to test whether the image elements were underneath any of the resulting $elementsUnderWhichNothingShouldFade (which is a list of elements).

jQuery: change class after conditional is met

I created this site where you have multiple sliders moving vertically using this example on stackoverflow > here < along with this fiddle.
The site when loaded has an overflow: hidden on the body and position fixed on my main content div(div class="content-fs row"). The idea is that when you first arrive on the page, you scroll through each slide and once you hit the last one, the position changes on the main content div(div class="content-fs row") from fixed to static and the overflow: hidden is removed from the body. I'm having trouble writing the conditional statement that says "if its the last slider, change the position." The jquery below is the code i'm using for the site along with the conditional statement that doesn't work.
Any pointers/advice would be greatly appreciated!
jquery:
function scrollLax(){
/*
initialize
*/
var scrollDown = false;
var scrollUp = false;
var scroll = 0;
var $view = $('#portfolio');
var t = 0;
var h = $view.height() - 250;
$view.find('.portfolio-sliders').each(function() {
var $moving = $(this);
// position the next moving correctly
if($moving.hasClass('from-bottom')) {
$moving.css('top', h); // subtract t so that a portion of the other slider is showing
}
// make sure moving is visible
$moving.css('z-index', 10);
});
var $moving = $view.find('.portfolio-sliders:first-child');
$moving.css('z-index', 10);
/*
event handlers
*/
var mousew = function(e) {
var d = 0;
if(!e) e = event;
if (e.wheelDelta) {
d = -e.wheelDelta/3;
} else if (e.detail) {
d = e.detail/120;
}
parallaxScroll(d);
}
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', mousew, false);
}
window.onmousewheel = document.onmousewheel = mousew;
/*
parallax loop display loop
*/
window.setInterval(function() {
if(scrollDown)
parallaxScroll(4);
else if(scrollUp)
parallaxScroll(-4);
}, 50);
function parallaxScroll(scroll) {
// current moving object
var ml = $moving.position().left;
var mt = $moving.position().top;
var mw = $moving.width();
var mh = $moving.height();
// calc velocity
var fromBottom = false;
var vLeft = 0;
var vTop = 0;
if($moving.hasClass('from-bottom')) {
vTop = -scroll;
fromBottom = true;
}
// calc new position
var newLeft = ml + vLeft;
var newTop = mt + vTop;
// check bounds
var finished = false;
if(fromBottom && (newTop < t || newTop > h)) {
finished = true;
newTop = (scroll > 0 ? t : t + h);
}
// set new position
$moving.css('left', newLeft);
$moving.css('top', newTop);
// if finished change moving object
if(finished) {
// get the next moving
if(scroll > 0) {
$moving = $moving.next('.portfolio-sliders');
if($moving.length == 0)
$moving = $view.find('.portfolio-sliders:last');
//this is where I am trying to add the if conditional statement.
if ('.portfolio-sliders:last')
$('.content-fs.row').css({'position': 'static'});
if('.portfolio-sliders:last' && (mt == 0))
$('html, body').removeClass('overflow');
} else {
$moving = $moving.prev('.portfolio-sliders');
if($moving.length == 0)
$moving = $view.find('.portfolio-sliders:first-child');
//reverse the logic and if last slide change position
if('.portfolio-sliders:first-child')
$('.content-fs.row').css({'position': 'fixed'});
}
}
// for debug
//$('#direction').text(scroll + "/" + t + " " + ml + "/" + mt + " " + finished + " " + $moving.text());
}
}
Your code as it is simply asks whether .portfolio-sliders:last exists. Seems you should be doing:
if ($moving == $('.portfolio-sliders:last') )
or something along those lines, instead checking whether the active slide is the last.

Event on margin change

I have an element with animated top margin. I need to detect if it isn't too close from the border, and if it is, scroll parent div to lower position, to prevent animated element from hiding. Here is an example:
http://jsfiddle.net/zYYBR/5/
This green box shouldn't be below the red line after clicking the "down" button.
Do you mean this?
var new_margin;
var step = 75;
var limit = $("#max")[0].offsetTop;
$('#down').click(function() {
var goStep = step;
var elHeight = $("#animated")[0].offsetTop + $("#animated")[0].offsetHeight;
if((elHeight + step) > limit)
{
goStep = limit - elHeight;
}
new_margin = goStep + parseInt($('#animated').css('margin-top'));
$("#animated").animate({marginTop: new_margin}, 1000);
});
http://jsfiddle.net/zYYBR/8/
EDIT: Or maybe something like that (of course you can improve the calculation, because currently it's very buggy with scroll):
var new_margin;
var step = 75;
$('#down').click(function () {
scroll(1000);
});
var scrollTimer = null;
$("#container").bind("scroll", function () {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(function () { scroll(1); }, 10);
});
function scroll(speed) {
var scrollStep, animationStep = step;
var currentBoxBottom = $("#animated")[0].offsetTop + $("#animated")[0].offsetHeight;
var nextCurrentBoxBottom = currentBoxBottom + step;
var limit = $("#max")[0].offsetTop + $("#container")[0].scrollTop;
if (nextCurrentBoxBottom > limit) {
if (limit >= $("#container")[0].scrollTop) {
scrollStep = $("#container")[0].scrollTop + nextCurrentBoxBottom - limit;
}
else {
scrollStep = $("#container")[0].scrollTop - nextCurrentBoxBottom - limit;
animationStep = nextCurrentBoxBottom - limit;
}
$("#container")[0].scrollTop = scrollStep;
}
new_margin = animationStep + parseInt($('#animated').css('margin-top'));
$("#animated").animate({ marginTop: new_margin }, speed);
}
http://jsfiddle.net/zYYBR/13/
Do you mean something like this?
I have the same visual result as Alex Dn did, but I added a little extra direction to what I think you're talking about. If it's what you're looking for I'll make updates:
var new_margin;
var step = 75;
var limit = $("#max")[0].offsetTop;
$('#down2').click(function() {
var anim = $("#animated");
var hrOff = $("#max").offset();
var thOff = anim.offset();
new_margin = Math.min(hrOff.top - thOff.top - anim.height(), 75);
console.log(new_margin, hrOff.top, thOff.top);
var st = 0;
if (new_margin < 75) {
st = 75 - new_margin;
//have container scroll by this much?
}
anim.animate({
marginTop: "+=" + new_margin
}, 1000);
});​
​
http://jsfiddle.net/zYYBR/10/

Categories

Resources