Jquery div movement on timer then repeat - javascript

I am having some issues with some code. I am trying to get a div to move in time with a slider show. Each time a new slide is shown the div moves.
This is what I came up with
setInterval(function() {
$( ".bar" ).animate({ "left": "+=13.5em" }, "slow" );
}, 3000);
This works great, the div keeps up with the slider. But It never stops. I have been trying to come up with the code to make this work but I can't seem to do it.
Once the div reaches a certain point I want it to go back to its starting point and then repet its animation over and over just as the image slider does.
Could I put another timer on another line of code to tell the div to go back to a point after a set duration? then the above code will keep playing the aniamtion? (I will give this ago now!)

Are you using a plugin for the slider? Some plugins you can set a callback like flexslider plugin:
$(elem).flexslider({
before: function(){
//event before slide transition
},
after: function(){
//event after slide transition
}
});

var count = $(".bar").length;
var current = 1;
setInterval(function() {
$( ".bar" ).animate({ "left": "+=13.5em" }, "slow" );
current++;
if(current == count) {
$( ".bar" ).animate({ "right": "+=" + (count*13.5) "em" }, "fast" );
current = 1;
}
}, 3000);
Maybe something like that?

var startPos = $(".bar").offset();
var endPos = $("foo").offset();
var foo = setInterval(function() {
var updatedPos = $( ".bar" ).position();
if (updatedPos.left === endPos.left) {
$(".bar").css({"left":startPos.left,"top":startPos.top});
}
$( ".bar" ).animate({ "left": "+=13.5em" }, "slow" );
}, 3000);
EDIT:
var pos = $(".bar").offset(); this gets the position relative to the document, you could also get the position relative to the parent node with .position() and then check on the interval if it hit the position, you could also just update the left right or top bottom, depending on your needs. but this would be a way to reset the position. You just need to know the start and end points.

Related

Auto-scroll embedded window only once when entering viewport. Can't scroll back up

I have an image embedded in a container with a background image to give the effect of scrolling within the page. Initially, I had the scrolling effect take place on page load, with this simple bit of script which worked perfectly.
$(window).on("load", function () {
$(".embedded_scroller_image").animate({ scrollTop: $('.embedded_scroller_image')[0].scrollHeight}, 2500, "easeInOutCubic");
}); // end on load
However, the element is too far down the page now and I want that animation to fire when the element enters 80% of the viewport. That part is also working fine with this code here (I'm using a scroll limiter to improve browser performance)
// limit scroll call for performance
var scrollHandling = {
allow: true,
reallow: function() {
scrollHandling.allow = true;
},
delay: 500 //(milliseconds) adjust to the highest acceptable value
};
$(window).on('scroll', function() {
var flag = true;
if(scrollHandling.allow) { // call scroll limit
var inViewport = $(window).height()*0.8; // get 80% of viewport
$('.embedded_scroller_image').each(function() { // check each embedded scroller
var distance = $(this).offset().top - inViewport; // check when it reaches offset
if ($(window).scrollTop() >= distance && flag === true ) {
$(this).animate({ scrollTop: $(this)[0].scrollHeight}, 2500, "easeInOutCubic"); //animate embedded scroller
flag = false;
}
});
} // end scroll limit
}); // end window scroll function
The problem is this: I want the autoscroll to happen once and then stop. Right now, it works on entering viewport, but if I then try to manually scroll the image, it keeps pushing back down or stutters. You can't get the element to scroll normally. I attempted to use the flag in the code to stop the animation, but couldn't get that to successfully work.
How can I have this animation fire when the element is 80% in the viewport, but then completely stop after one time?
Here is a codepen I mocked up as well http://codepen.io/jphogan/pen/PPQwZL?editors=001 If you scroll down, you will see the image element autoscroll when it enters the viewport, but if you try to then scroll that image up in its container, it won't work.
Thanks!
I have tweaked your script a bit:
// limit scroll call for performance
var scrollHandling = {
allow: true,
reallow: function() { scrollHandling.allow = true; },
delay: 500 //(milliseconds) adjust to the highest acceptable value
};
$(window).on('scroll', function() {
if(scrollHandling.allow) { // call scroll limit
var inViewport = $(window).height()*0.8; // get 80% of viewport
$('.embedded_scroller_image').each(function() { // check each embedded scroller
var distance = $(this).offset().top - inViewport; // check when it reaches offset
if ($(window).scrollTop() >= distance ) {
$(this).animate({ scrollTop: $(this)[0].scrollHeight}, 2500, "easeInOutCubic"); //animate embedded scroller
scrollHandling.allow = false;
}
});
} // end scroll limit
}); // end window scroll function
I have kicked out your flag and simply made use of scrollHandling.allow declared already.
Try if it works for you :)
Cheers!

Animating Top and Bottom Position with jQuery

i'm trying to animate with jQuery.
http://jsfiddle.net/g8mQu/
$('#down').on("click", function() {
$('#inner').animate({ "top": "-=50px" }, "slow" );
});
That's my code pretty much and it works in this demo, but i'm trying to implement this into a Bootstrap framework site. The css is the same though, the wrapper is a container and the scrollable div is a col-xs div.
This should work fine but whenever I click a button it doesn't add 50 to the position but sets the position to 50 / -50 even though i'm using the "+=50" command.
try with
$('#down').on("click", function() {
var $inner = $('#inner');
$inner.animate({ "top": $inner.css("top") - 50 }, "slow" );
});

how to stop animation once max width is reached

I am working to make a slider that moves continuously while the users mouse is positioned over the arrow. It works but it keeps moving even when the content has ended.
How can I make it stop so that the forward/back motion is disabled once all the slides have been viewed, or so that they can't go backwards when they are viewing the first slide?
My code is below - open to other methods to achieve this type of slider if what I have is bad.
$(document).ready(function() {
var timer;
$("#leftarrow").hover(function() {
timer = setInterval(function() {slideLeft();}, 50);
}, function() {
clearInterval(timer);
});
$("#rightarrow").hover(function() {
timer = setInterval(function() {slideRight();}, 50);
}, function() {
clearInterval(timer);
});
function slideLeft() {
$("img#background").stop().animate({
'left': '-=200px'
}, 50);
$(".mid").stop().animate({
'left': '-=20px'
}, 50);
console.log('alert');
}
function slideRight() {
$("img#background").stop().animate({
'left': '-=200px'
}, 50);
$(".mid").stop().animate({
'left': '+=20px'
}, 50);
}
});
Here is a fiddle with my slider: http://jsfiddle.net/rYYDv/
You can use an additional if:
For slide left:
if(($(".mid").position().left) >= -500){ .. }
For slide right:
if(($(".mid").position().left) <= -10){ .. }
Disadvantage: You have to take care of the correct values manually. Which is not a problem, if the pictures don't change very often.
You should probably also add an additional else to ensure a correct final position (for the animate left property). But i think you get the idea.
http://jsfiddle.net/rYYDv/2/
I do not have enough points to comment on this post; hence, I'm writing it down here -
Similar post: How to make the Animate jQuery method stop at end of div?

jquery dropline to hold second when mouse is hover out

Is there a way to get this behavior on this dropline menu?Need second or thrid level to stay active for one second when mouse is hover out from menu items.
To clarify, you're looking for some kind of delayed reaction to the mouse's movement? If so, check out this jQuery hoverintent plugin: http://cherne.net/brian/resources/jquery.hoverIntent.html
EDIT: I think you'll need to edit your menu script to replace any instance of .hover with .hoverIntent. I had trouble testing this in jsfiddle, but see if it works:
var droplinemenu={
arrowimage: {classname: 'downarrowclass', src:'http://www.odzaci.rs/wp-content/themes/typo/images/down.gif', leftpadding: 5}, //customize down arrow image
animateduration: {over: 200, out: 300}, //duration of slide in/ out animation, in milliseconds
buildmenu:function(menuid){
jQuery(document).ready(function($){
var $mainmenu=$("#"+menuid+">ul")
var $headers=$mainmenu.find("ul").parent()
$headers.each(function(i){
var $curobj=$(this)
var $subul=$(this).find('ul:eq(0)')
this._dimensions={h:$curobj.find('a:eq(0)').outerHeight()}
this.istopheader=$curobj.parents("ul").length==1? true : false
if (!this.istopheader)
$subul.css({left:0, top:this._dimensions.h})
var $innerheader=$curobj.children('a').eq(0)
$innerheader=($innerheader.children().eq(0).is('span'))? $innerheader.children().eq(0) : $innerheader //if header contains inner SPAN, use that
$innerheader.append(
'<img src="'+ droplinemenu.arrowimage.src
+'" class="' + droplinemenu.arrowimage.classname
+ '" style="border:0; padding-left: '+droplinemenu.arrowimage.leftpadding+'px" />'
)
// THIS IS THE PART I REPLACED
var config = {
over: function(e){
var $targetul=$(this).children("ul:eq(0)")
if ($targetul.queue().length<=1) //if 1 or less queued animations
if (this.istopheader)
$targetul.css({left: $mainmenu.offset().left, top: $mainmenu.offset().top+this._dimensions.h})
if (document.all && !window.XMLHttpRequest) //detect IE6 or less, fix issue with overflow
$mainmenu.find('ul').css({overflow: (this.istopheader)? 'hidden' : 'visible'})
$targetul.slideDown(droplinemenu.animateduration.over)
},
timeout: 1000, // number = milliseconds delay before onMouseOut
out: function(e){
var $targetul=$(this).children("ul:eq(0)")
$targetul.slideUp(droplinemenu.animateduration.out)
}
};
$curobj.hoverIntent( config );
}) //end $headers.each()
$mainmenu.find("ul").css({display:'none', visibility:'visible', width:$mainmenu.width()})
}) //end document.ready
}
}

deactivate button on gallery slider

I'm am trying to make my javascript/jquery slider button deactivated when it reaches the the end of the scrolling images( when the images have moved all the way to the right, the MoveRight button must be deactivated and only leave MoveLeft button active, same for the move LeftButton), can anybody help with this ? Im not sure if im using
.attr() and removeAttr() correctly. I have pasted my code below.
<script type="text/javascript">
$(document).ready(function(){
//Check width of Gallery div
var galleryWidth = $("#Gallery").innerWidth();
//Check width of GalleryItem
var NoListed = $("ul.GalleryItem li").length;
var galleryItemWidth = 1881;
$('.MoveRight')
$('.GalleryItem').css('width', galleryItemWidth);
//Check width of Gallery div on resize
$(window).resize(function(){
var galleryWidth = $("#Gallery").innerWidth();
});
$('.MoveLeft').click(function() {
$(".GalleryItem2").animate({"left": "-=350px"}, "slow");
$(".GalleryItem3").animate({"left": "-=280px"}, "slow");
$(".GalleryItem").animate({
left: '-=230',
}, "slow", function() {
position = $(".GalleryItem").position();
galleryItemLeft = position.left;
if(galleryItemLeft <= galleryWidth - galleryItemWidth) {
$('.MoveLeft').removeAttr('disabled');}
else{
$('.MoveLeft').attr('disabled','disabled');
$('.MoveRight').attr('disabled','disabled');
}
});
});
$('.MoveRight').click(function() {
$(".GalleryItem2").animate({"left": "+=350px"}, "slow");
$(".GalleryItem3").animate({"left": "+=280px"}, "slow");
$(".GalleryItem").animate({
left: '+=230',
}, "slow", function() {
position = $(".GalleryItem").position();
galleryItemLeft = position.left;
if(galleryItemLeft >= "0") {
$('.MoveLeft').removeAttr('disabled');}
else{
$('.MoveLeft').attr('disabled','disabled');
$('.MoveRight').attr('disabled','disabled');
}
});
});
});
</script>
first of all, I see you doing the following:
//Check width of Gallery div on resize
$(window).resize(function(){
var galleryWidth = $("#Gallery").innerWidth();
});
I like the fact that you keep your variables local, but the var keyword should be omitted in this case. You've declared galleryWidth already in the function that encloses this resize callback, so by omitting the var keyword here, the value will be assigned to the variable you use in your script, with this va keyword, you create a new galleryWidth variable, only visible in the resize callback, and therefore never used.
now for the enabling and disabling of the buttons:
you could keep a currentitem counter, and update it every time the moveright or moveleft buttons are clikced. When this counter reaches 0, you disable the moveleft button, when it reaches the number of items, you disable the moveright button, and enable them otherwise.

Categories