jquery slide div by changing margin - javascript

I'm making left/right buttons to make a div slide. It slides by changing the left margin. What I'm trying to do is have it check the left margin and then add/subtract pixels to it. So when the page loads, left margin should be 0. Then you click the button and it checks the margin, finds it's 0, adds 150 and sets the left margin to 150. And then if you click it again, it checks the margin, finds it's 150 and adds another 150 and sets the margin to 300.
It succeeds in moving the margin from 0 to 150, but i can't get it to go to 300. I'm thinking it's not able to determine the margin correctly. Any ideas how I can fix this? Thanks!
$('#left').click(function(){
var pos=$('#contentarea').css("margin-left").replace('px', '');
pos=pos+150;
$('#contentarea').animate({ 'margin-left': '-' + pos + 'px'}, 1000);
return false;
});

There is no need to get current margin-left value, you can use the '+=%value%' and '-=%value%' operators. This will add/substract from the current value the specified value.
$('#left').click(function(){
$('#contentarea').animate({ 'margin-left': '+=150px'}, 1000);
return false;
});

try this,
use for Get Margin
$('#contentarea').css("margin-left")
it will return margin default is "PX".
Use For Set Margin
$('#contentarea').css("margin-left","Your Size");
Default size is "PX" not need to provide size with "PX".
Try this function
$(document).ready(function () {
$('#contentarea').css("margin-left", "0");
});
$('#left').click(function () {
var pos = $('#contentarea').css("margin-left");
var size = 0;
if (pos == "0px") {
$('#contentarea').css("margin-left", "150");
}
else {
size = parseInt(pos.slice(0, -2));
size = size + 150;
}
var pos = $('#contentarea').css("margin-left", size);
$('#contentarea').animate({ 'margin-left': '-' + pos }, 1000);
return false;
})

Use parseInt instead of replace to get css margin left value.
$('#left').click(function(){
var pos = parseInt($('#contentarea').css("margin-left")) + 150;
$('#contentarea').animate({'margin-left' : '-' + pos + 'px'}, 1000);
return false;
});

Related

Animate element based on scroll position inside absolute div with overflow: scroll

I'm trying to animate an element based on the scroll position inside a div with the properties position: absolute and overflow: scroll. The code I've got to so far is basing the animation based on the position on the page position, and changing the opacity. I want to change the property filter: blur(value); Below is the code (opacity, not div based scroll) as it exists now:
var header = $('div.modal-container figure.still');
var range = 200;
$(window).on('scroll', function() {
var scrollTop = $(this).scrollTop(),
height = header.outerHeight(),
offset = height / 2,
calc = 1 - (scrollTop - offset + range) / range;
header.css({
'opacity': calc
});
if (calc > '1') {
header.css({
'opacity': 1
});
} else if (calc < '0') {
header.css({
'opacity': 0
});
}
});
Any help on how I can accomplish this?
If you have in calc variable radius of blur in pixels, try something like this:
header.css({
'filter': `blur(${calc}px)`
});
if (calc < 0) {
header.css({
'filter': 'none'
});
}

Stop animation at certain position on page [jQuery]

I have a div that moves across the page on a keydown event listener. I'm trying to find a way to make it stop after either a certain number of keydowns (calculated by step * clicks > screen size) or when the animated div reaches the end of the screen, which I guess would need to be responsive to screen size.
Currently the animate continues to fire on keydown and the div will scroll off out of view.
An example of this is the second demo on this page: http://api.jquery.com/animate/
You can click left or right until the block moves out of view. How would I contain it to it's uh, container?
here's my jsfiddle: https://jsfiddle.net/vidro3/1a8tnuer/
var count1 = 0;
var count2 = 0;
// 1. Get two divs to move on different key presses;
$(function(){
$(document).keydown(function(e){
switch (e.which){
case 39: //lright arrow key
count2++;
$('.box2').animate({
left: '+=50'
});
break;
case 90: //z key
count1++;
$('.box1').animate({
left: '+=50'
});
break;
}
});
});
// 2. Get one div to move on button click;
$(function(){
$( '#start' ).click(function() {
alert('Chug that Duff!');
var rabbit = $(".rabbit");
rabbit.animate({left: '+=100%'}, 'slow');
});
});
$(function(){
var winPos = $('#background').width();
if (winPos/50 > count1)
alert('Homer Wins!');
else if (winPos/50 > count2)
alert('Barney Wins!');
});
Just add a conditional to the animation:
var maxLeft = $(window).width() - $('.box1').width();
// If the box's x-position is less than the max allowed, then animate
if ($('.box1').position().left < maxLeft) {
$('.box1').animate({
left: '+=50'
});
}
The value (window width - box width) is the point at which the box is at the end of the screen. Note that your step size may take the box past the end of the screen depending on the current window size (it's probably not divisible by 50, for example), so you may want something like this instead:
var stepSize = 50;
var maxLeft = $(window).width() - $('.box1').width();
// If the box's x-position is less than the max allowed, then animate
if ($('.box1').position().left < maxLeft) {
var diff = maxLeft - $('.box1').position().left;
// If the next step would take the box partially off the screen
if (diff < stepSize) {
$('.box1').animate({
left: '+=' + diff
});
} else {
$('.box1').animate({
left: '+=' + stepSize
});
}
}
Edit: here's a shorter version using the ternary operator:
var stepSize = 50;
var maxLeft = $(window).width() - $('.box1').width();
// If the box's x-position is less than the max allowed, then animate
if ($('.box1').position().left < maxLeft) {
var diff = maxLeft - $('.box1').position().left;
$('.box1').animate({
left: '+=' + (diff < stepSize ? diff : stepSize)
});
}

How to add a jQuery scrollTop offset?

I'm trying to get the div to snap to the center of the viewport, right now it just snaps to the top. I was trying to put an offset of 50% but can only get it in px's.
EDIT
I added a new fiddle where I tried to include $(window).scrollTop() / 2)
http://jsfiddle.net/kZY9R/84/
$("#item").offset().top - 100
var body = $("html, body");
var items = $(".item");
var animating = false;
$(window).scroll(function() {
clearTimeout($.data(this, 'scrollTimer'));
if (!animating) {
$.data(this, 'scrollTimer', setTimeout(function() {
items.each(function(key, value) {
if ($(value).offset().top > $(window).scrollTop()) {
animating = true;
$(body).stop().animate( { scrollTop: $(value).offset().top }, 1000,'swing');
setTimeout(function() { animating = false; }, 2000);
return false;
}
});
}, 50));
}
});
I found this:
$('html, body').animate({scrollTop: $('#your-id').offset().top -100 }, 'slow');
Source: Run ScrollTop with offset of element by ID
Here's the trick to keep your viewport centralized on a particular div.
Prerequisites
You need to take into account the following three criteria to be able to centralize the viewport on a given item:
height of the last item that appeared on the viewport.
The distance of the last item from the top of the page, i.e. the offset().top of the item.
The height value of the viewport (i.e the window object).
Calculating Vertical Position of the Item
The required scrollTop value for the window can be calculated as in the following:
var scrollValue = itemOffset // offset of the item from the top of the page
- .5 * windowHeight // half the height of the window
+ .5 * itemHeight; // half the height of the item
You are basically, moving the top of your viewport to the item under view's top offset initially. This, as you've already experienced, snaps the item to the top of the window.
The real magic part comes when you subtract half of the window's height to go halfway along it vertically, and then shifting your view back down by adding half the item's height. This makes the item appear vertically centralized with regards to the viewport.
Note:
To be able to query the last item that appeared on the viewport, you have to iterate over all of the elements that have a top offset value (i.e. offset().top) less than or equal to that of the window's scrollTop value:
$.each($('.item'), function(i, value) {
if ($(viewport).scrollTop() >= $(this).offset().top) {
lastItemInView = $(this);
}
});
With the above, the lastItemInView variable will always end up with the last element visible in the window.
Demo
Not sure if you figured this out yet or not but I took some code from this answer (How to tell if a DOM element is visible in the current viewport?) that shows how to tell if an element is visible in the view port.
Using that I modified your code to loop through each item and find the first visible one in the viewport and then center that one also factoring in the margin-top you have. Let me know if this helps!
Fiddle: http://jsfiddle.net/kZY9R/86/
var body = $("html, body");
var items = $(".item");
var animating = false;
$(window).scroll(function() {
clearTimeout($.data(this, 'scrollTimer'));
if (!animating) {
$.data(this, 'scrollTimer', setTimeout(function() {
items.each(function(key, value) {
if (elementInViewport(value)) {
animating = true;
var margin = parseInt($(value).css('margin-top'));
$('html,body').animate({
scrollTop: $(value).offset().top - ($(window).height() + margin - $(value).outerHeight(true)) / 2
}, 200);
setTimeout(function() {
animating = false;
}, 2000);
return false;
}
});
}, 50));
}
});
function elementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while (el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
}

How to use math.random() with for loop

I want to change the position of div with for loop ..
I made an animation .. When i click a div ( circle ) it moves to a position that is being determined with Math.random() ..
I dont want to click the div to move to another position .
I want to use for loop method and i want div to move another position in every 2 seconds or some seconds ..
Do you have any advise .. Thanks
Click to see how it is
$(document).ready(function () {
$("#circle").click(function () {
var width = Math.random();
var yeniwidth = width * 500;
margin = Math.round(yeniwidth);
$("#circle").css("margin-top", margin + "px");
var height = Math.random();
var yeniheight = height * 1000;
margin2 = Math.round(yeniheight);
$("#circle").css("margin-left", margin2 + "px");
});
});
Codepen
You don't really need a for-loop to do that. Instead of executing the code after clicking the div, you could just use the setInterval function instead:
$(document).ready(function () {
window.setInterval(function(){
var width = Math.random();
var yeniwidth = width * 500;
margin = Math.round(yeniwidth);
$("#circle").css("margin-top", margin + "px");
var height = Math.random();
var yeniheight = height * 1000;
margin2 = Math.round(yeniheight);
$("#circle").css("margin-left", margin2 + "px");
}, 5000);
});
Just change the number 5000 to adjust the time that should pass before the code is executed again (1000ms is 1 second).
On Codepen

Popover Placement depending up on space available.

Please have a look at the attached image.
As you can see i am showing a popover. Basically i want to change the placement of the popover depending up on the space available( left or right ). Right now its going outside of an image.
Its a fancy-box(iframe)
Showing the popover using this code.
// Position and show the message.
this.message
.css({
left: (tPosition.left + "px"),
top: ((tPosition.top + t.outerHeight()) + "px")
})
.show();
I would do something like this:
this.message
.css({
left : function () {
if ( tPosition.left + $(this).width() >= $(this).parent().width() ) {
return $(this).parent().width() - $(this).width();
}
else {
return tposition.left;
}
},
top : function () {
if ( tPosition.top + $(this).height() > $(this).parent().height() ) {
return $(this).parent().height() - $(this).height();
}
else {
return tposition.top;
}
}
});
Basically you need to check if the popup is going to exceed your containing box boundaries before you show it and adjust it appropriately. On the horizontal axis this is as simple as making sure that mouse position x + the width of the popup is not greater than the width of the parent container. On the vertical axis you want to make sure that mouse position y + the popup height is not greater than the parent container height.

Categories