Animate jQuery not working as expected - javascript

I have a FB feed in a web page
When I press the Prev and Next buttons, the next and previous news feeds are displayed. But I would like to use the animate function when scrolling.
I have tried to use this lines of code:
$('html, body').stop().animate({
scrollTop: $scrollItems.eq(currentFbDiv).offset().top
}, 200);
but it not works as expected.
Can you please guide me how can I use in my example? Thanks
<script>
jQuery(document).ready(function($){
var pagePositon = 0,
sectionsSeclector = $(".cff-item"),
$scrollItems = $(sectionsSeclector),
offsetTolorence = 20,
fbDivHeights = [],
result = [],
currentFbDiv = 0,
$fbDivWrapper = $('#cff'),
pageMaxPosition = $scrollItems.length-1;
sectionsSeclector.each(function(index, item) {
var sum = fbDivHeights.reduce(function(a, b) { return a + b; }, 0);
fbDivHeights.push( $(item).outerHeight());
result = fbDivHeights.map((s => a => s += a)(0));
});
//Map the sections:
$scrollItems.each(function(index,ele) {
$(ele).attr("debog",index).data("pos",index);
});
// Bind to scroll
$(window).bind('scroll',upPos);
//Move on click:
$('#facebook_ticker_controls a').click(function(e){
//alert("aaa");
if ($(this).hasClass('next') && currentFbDiv < pageMaxPosition) {
currentFbDiv++;
$fbDivWrapper.css('margin-top', -result[currentFbDiv-1]);
/* pagePositon++;*/
$('html, body').stop().animate({
scrollTop: $scrollItems.eq(currentFbDiv).offset().top
}, 200);
}
if ($(this).hasClass('prev') && currentFbDiv!= 0 && currentFbDiv <= pageMaxPosition) {
if(currentFbDiv == 1) {
$fbDivWrapper.css('margin-top', '0px');
} else {
currentFbDiv--;
$fbDivWrapper.css('margin-top', -result[currentFbDiv-1]);
}
/*$('html, body').stop().animate({
scrollTop: $scrollItems.eq(pagePositon).offset().top
}, 300);
return false;*/
}
return false;
});
//Update position func:
function upPos(){
var fromTop = $(this).scrollTop();
var $cur = null;
$scrollItems.each(function(index,ele){
if ($(ele).offset().top < fromTop + offsetTolorence)
$cur = $(ele);
});
if ($cur != null && pagePositon != $cur.data('pos')) {
pagePositon = $cur.data('pos');
}
}
});
</script>
<div class="tab-content">
<div class="tab-pane active fade in">
<ul class="list-unstyled" id="facebook_ticker">
<?php echo do_shortcode("[custom-facebook-feed]"); ?>
</ul>
</div>
<div id="facebook_ticker_controls" class="ticker-controls">
<div style="position: absolute; z-index: 1000; background-color: rgba(0,0,0,.7); height: 35px; width: 350px;">
<span class="glyphicon glyphicon-chevron-down"></span> Previous
Next <span class="glyphicon glyphicon-chevron-up"></span>
</div>
</div>
</div><!-- end tab-content -->

Related

Make Fullpage-Scroll-Script less static

Heyo,
I got a little Fullpage-Scroll-Script and I want to make it a bit less static. So instead of calling every single Div by a different Class (.one, .two, .tree...) I want to make the script work if all Divs have only one Class (.page). I tried it myself with the .each() function from jQuery ... but I couldn't get it to work.
Here is the current Script:
// Fullpage Scroll Script
function ScrollHandler(pageClass) {
var page = $('.' + pageClass);
var pageStart = page.offset().top;
var pageJump = false;
function scrollToPage() {
pageJump = true;
$('html, body').animate({
scrollTop: pageStart
}, {
duration: 1000,
easing:'swing',
complete: function() {
pageJump = false;
}
});
}
window.addEventListener('wheel', function(event) {
var viewStart = $(window).scrollTop();
if (!pageJump) {
var pageHeight = page.height();
var pageStopPortion = pageHeight / 2;
var viewHeight = $(window).height();
var viewEnd = viewStart + viewHeight;
var pageStartPart = viewEnd - pageStart;
var pageEndPart = (pageStart + pageHeight) - viewStart;
var canJumpDown = pageStartPart >= 0;
var stopJumpDown = pageStartPart > pageStopPortion;
var canJumpUp = pageEndPart >= 0;
var stopJumpUp = pageEndPart > pageStopPortion;
var scrollingForward = event.deltaY > 0;
if ( ( scrollingForward && canJumpDown && !stopJumpDown) || (!scrollingForward && canJumpUp && !stopJumpUp)) {
event.preventDefault();
scrollToPage();
}
} else {
event.preventDefault();
}
});
}
new ScrollHandler('one');
new ScrollHandler('two');
new ScrollHandler('three');
* {
margin:0;
padding:0;
}
.page {
height: 100vh;
}
.one { background-color: blue; }
.two { background-color: green; }
.three { background-color: orange; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page one"></div>
<div class="page two"></div>
<div class="page three"></div>
So instead of using:
new ScrollHandler('one');
new ScrollHandler('two');
new ScrollHandler('three');
I tried to use this:
$('.page').each(function() {
new ScrollHandler('page');
}
But it only worked for the first Div.
You need to pass $(this) in each loop and change the page variable to get directly the parameter :
// Fullpage Scroll Script
function ScrollHandler(pageClass) {
var page = pageClass;
var pageStart = page.offset().top;
var pageJump = false;
function scrollToPage() {
pageJump = true;
$('html, body').animate({
scrollTop: pageStart
}, {
duration: 1000,
easing: 'swing',
complete: function() {
pageJump = false;
}
});
}
window.addEventListener('wheel', function(event) {
var viewStart = $(window).scrollTop();
if (!pageJump) {
var pageHeight = page.height();
var pageStopPortion = pageHeight / 2;
var viewHeight = $(window).height();
var viewEnd = viewStart + viewHeight;
var pageStartPart = viewEnd - pageStart;
var pageEndPart = (pageStart + pageHeight) - viewStart;
var canJumpDown = pageStartPart >= 0;
var stopJumpDown = pageStartPart > pageStopPortion;
var canJumpUp = pageEndPart >= 0;
var stopJumpUp = pageEndPart > pageStopPortion;
var scrollingForward = event.deltaY > 0;
if ((scrollingForward && canJumpDown && !stopJumpDown) || (!scrollingForward && canJumpUp && !stopJumpUp)) {
event.preventDefault();
scrollToPage();
}
} else {
event.preventDefault();
}
});
}
$('.page').each(function() {
new ScrollHandler($(this));
})
* {
margin: 0;
padding: 0;
}
.page {
height: 100vh;
}
.one {
background-color: blue;
}
.two {
background-color: green;
}
.three {
background-color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page one"></div>
<div class="page two"></div>
<div class="page three"></div>
JSfiddle: https://jsfiddle.net/fw8h7v4q/

Linking to a certain position of another page

I have a mainpage called index.html with a menu linking to certain positions (parts) on this mainpage. This is done via the variable 'data-slide' (see below) that is behind the 'buttons' in the menu. This works well on the mainpage. However, how can I do this when I'm on another html page than the mainpage, jumping to a certain position (part) of the mainpage?
<div id="nav" class="right">
<ul class="navigation">
<li data-slide="1">Home</li>
<li data-slide="2">Products</li>
<li data-slide="4">Trade fairs</li>
<li data-slide="6">Company</li>
<li data-slide="8">Careers</li>
<li data-slide="10">Contact</li>
<li class="clear"></li>
</ul>
</div>
Javascript:
var links = $('.navigation').find('li');
slide = $('.slide');
button = $('.button');
mywindow = $(window);
htmlbody = $('html,body');
slide.waypoint(function (event, direction) {
dataslide = $(this).attr('data-slide');
if (direction === 'down') {
$('.navigation li[data-slide="' + dataslide + '"]').addClass('active').prev().removeClass('active');
$('.navigation li[data-slide="1"]').removeClass('active');
}
else {
$('.navigation li[data-slide="' + dataslide + '"]').addClass('active').next().removeClass('active');
}
});
mywindow.scroll(function () {
if (mywindow.scrollTop() == 0) {
$('.navigation li[data-slide="1"]').addClass('active');
$('.navigation li[data-slide="2"]').removeClass('active');
}
});
function goToByScroll(dataslide) {
var goal = $('.slide[data-slide="' + dataslide + '"]').offset().top;
if (mywindow.scrollTop()<goal) {
var goalPx = goal + 1;
} else {
var goalPx = goal - 1;
}
htmlbody.animate({
scrollTop: goalPx
}, 2500, 'easeInOutQuint');
}
links.click(function (e) {
e.preventDefault();
dataslide = $(this).attr('data-slide');
goToByScroll(dataslide);
});
button.click(function (e) {
e.preventDefault();
dataslide = $(this).attr('data-slide');
goToByScroll(dataslide);
});
window.setTimeout(function(){
if(window.location.hash){
var $target = $(window.location.hash).closest("#bgaboutbody");
if($target.length)
$('html, body').animate({scrollTop: $target.offset().top}, 1000);
}
}, 100);
Please try this link:-anchor linking to a certain position of the page

How to get image to original position

Fiddle:
https://jsfiddle.net/r73b14y5/3/
script works fine but cant get the image to slide back to the original location if another link is not clicked.
at the moment the image stays where ever it last hovered over, instead of only staying at a link if the new link was clicked. and sliding back to the original link if nothing is clicked.
Also whats the best way to delay the hover state so as the mouse flys over the element quickly it doesnt activate. hover intent.
HTML:
<div class="bblock1" style="height:100%;">
<div class="container">
<div class="bodymainMaxS">
<div class='tabbed_content'>
<div class='tabs'>
<div class='moving_bg'> </div>
<span class='tab_item tab_item_color'>OVERVIEW</span>
<span class='tab_item'>THE SCIENCE</span>
<span class='tab_item'>ORDER</span>
<span class='tab_item'>REPLACEMENT FILTERS</span>
</div>
</div>
</div>
</div>
<div class="bblock3" style="height:100%;">
<div class="container">
<div class="bodymainMaxS">
</div>
</div>
</div>
** key part of Script:**
$(".tab_item").mouseover(function() {
var $this = $(this);
$this.parent().find(".moving_bg").stop().animate({
left: $this.position()['left']
}, { duration: 300 });
});
rest of script
var TabbedContent = {
current: {i:null, obj:null},
init: function() {
$(".tab_item").click(function() {
$(".tab_item").removeClass("tab_item_color");
$(this).addClass("tab_item_color");
var $this = $(this);
TabbedContent.slideContent($this);
});
TabbedContent.current.i = 0;
TabbedContent.current.obj = $(".tabslider li").eq(0);
},
slideContent: function($obj) {
var $container = $obj.closest(".tabbed_content"),
$contentContainer = $('.bodymainMaxS'),
$tabslider = $contentContainer.find(".tabslider");
var i = $obj.index() - 1;
var $lis = $tabslider.find("li");
$new = $lis.eq(i);
if(i === TabbedContent.current.i) {
return;
}
$lis.hide().filter($new.add(TabbedContent.current.obj)).show();
var margin_1 = (i > TabbedContent.current.i) ? 0 : -$new.width();
var margin_2 = (i < TabbedContent.current.i) ? 0 : -$new.width();
$tabslider.stop().css({
marginLeft: margin_1 + "px"
}).animate({
marginLeft: margin_2 + "px"
}, 400);
TabbedContent.current.i = i;
TabbedContent.current.obj = $new;
}
}
TabbedContent.init();
Here is the complete JS fixed replace whole javascript with this one (you can test here with JSFiddle )
removed TabbedContent because that was not being used (if you need that you can always copy from your question)
var isTabSelected = false;
var lastSelectedTabLeftPos;
$(".tab_item").mouseover(function() {
var $this = $(this);
$this.parent().find(".moving_bg").stop().animate({
left: $this.position()['left']
}, { duration: 300 });
});
$( ".tab_item" ).mouseout(function() {
if(isTabSelected){
$(".moving_bg").stop().animate({
left: ""+lastSelectedTabLeftPos
}, { duration: 300 });
}else
{
$(".moving_bg").stop().animate({
left: "0"
}, { duration: 300 });
}
});
$(".tab_item").click(function() {
isTabSelected = true;
var $this = $(this);
lastSelectedTabLeftPos = $this.position()['left'];
});

Fix Popup to lift up smoothly

I create a pop-up dialog box which lift up on left bottom while user scroll page.
You can see it live here- http://uposonghar.com/jobs/odesk/daniel/new/
My problem is it does not smoothly lift up first time, then it is ok. Anyone please suggest any idea to fix it. Need to make smoothly lift up.
My code
<div id="scrolltriggered" style="width: 310px; left: 10px; bottom: 10px;">
<div id="inscroll">
x<a href="http://www.google.com" target="_blank"><img src="images/buyersguide.png" alt="Free Resources" height="235" width="310">
</a>
</div>
</div>
<script type="text/javascript">
var stb = {
hascolsed: false,
cookieLife: 7,
triggerHeight: 30,
stbElement: ""
};
</script>
Javascript Code-
if (typeof stb === "undefined")
var stb = {};
jQuery(document).ready(function () {
jQuery("#closebox").click(function () {
jQuery('#scrolltriggered').stop(true, true).animate({ 'bottom':'-210px' }, 700, function () {
jQuery('#scrolltriggered').hide();
stb.hascolsed = true;
jQuery.cookie('nopopup', 'true', { expires: stb.cookieLife, path: '/' });
});
return false;
});
stb.windowheight = jQuery(window).height();
stb.totalheight = jQuery(document).height();
stb.boxOffset = '';
if (stb.stbElement != '') {
stb.boxOffset = jQuery(stb.stbElement).offset().top;
}
jQuery(window).resize(function () {
stb.windowheight = jQuery(window).height();
stb.totalheight = jQuery(document).height();
});
jQuery(window).scroll(function () {
stb.y = jQuery(window).scrollTop();
stb.boxHeight = jQuery('#scrolltriggered').outerHeight();
stb.scrolled = parseInt((stb.y + stb.windowheight) / stb.totalheight * 100);
if (stb.showBox(stb.scrolled, stb.triggerHeight, stb.y) && jQuery('#scrolltriggered').is(":hidden") && stb.hascolsed != true) {
jQuery('#scrolltriggered').show();
jQuery('#scrolltriggered').stop(true, true).animate({ 'bottom':'10px' }, 700, function () {
});
}
else if (!stb.showBox(stb.scrolled, stb.triggerHeight, stb.y) && jQuery('#scrolltriggered').is(":visible") && jQuery('#scrolltriggered:animated').length < 1) {
jQuery('#scrolltriggered').stop(true, true).animate({ 'bottom':-stb.boxHeight }, 700, function () {
jQuery('#scrolltriggered').hide();
});
}
});
jQuery('#stbContactForm').submit(function (e) {
e.preventDefault();
stb.data = jQuery('#stbContactForm').serialize();
jQuery.ajax({
url:stbAjax.ajaxurl,
data:{
action:'stb_form_process',
stbNonce:stbAjax.stbNonce,
data:stb.data
},
dataType:'html',
type:'post'
}).done(function (data) {
jQuery('#stbMsgArea').html(data).show('fast');
});
return false;
});
});
(function(stb_helpers) {
stb_helpers.showBox = function(scrolled, triggerHeight, y) {
if (stb.isMobile()) return false;
if (stb.stbElement == '') {
if (scrolled >= triggerHeight) {
return true;
}
}
else {
if (stb.boxOffset < (stb.windowheight + y)) {
return true;
}
}
return false;
};
stb_helpers.isMobile = function(){
if (navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
) {
return true;
}
else return false;
}
})(stb);
i think you need css changes, copy paste the following in your aspx
<div style="width: 310px; left: 10px; bottom: -225px; display: none;" id="scrolltriggered">
Hope it Helps
All you need to do is add the following line to your document ready as the First line
$("#scrolltriggered").css({bottom: -235});
This will make sure that the popup is scrolled to the bottom by 235px. If you need it to scroll variably add the Elements height by using jquery selector.
See the Fiddle Here

Blinking divs like traffic lights?

I have this website: backlinkbeat.com. To the down, there are 3 divs having the background images. Each background-image includes a number like "1", "2", "3". I want those divs to blink as traffic lights respectively.
The script I wrote is not blinking the lights correctly as you can see in the link which means that it is not blinking the correct order. I want to blink them in the way are shown in the markup:
<div style="float:left; height:400px;">
<div style=" margin-top:50px;">
<div class="list cufon one" id="blink1" style="width:420px;">put you on just any, <span style="color:#1fbfd1;">www.yourwebsite.com</span>
</div>
<div class="list cufon two" id="blink2" style="width:420px;">Press <span style="color:#1fbfd1;">"do it"</span>
</div>
<div class="list cufon three" id="blink3" style="width:420px;">see the backlinks <span style="color:#1fbfd1;">roll in!</span>
</div>
</div>
</div>
The script I wrote which donot work correctly is:
setInterval(function () {
setTimeout(function(){
var vis1 = $("#blink1").css("visibility");
vis1 = (!vis1 || vis1 == "visible") ? "hidden" : "visible";
$("#blink1").css("visibility", vis1);
}, 1000);
}, 1000);
setInterval(function() {
setTimeout(function(){
var vis2 = $("#blink2").css("visibility");
vis2 = (!vis2 || vis2 == "visible") ? "hidden" : "visible";
$("#blink2").css("visibility", vis2);
}, 2000);
}, 2000);
setInterval(function() {
setTimeout(function(){
var vis3 = $("#blink3").css("visibility");
vis3 = (!vis3 || vis3 == "visible") ? "hidden" : "visible";
$("#blink3").css("visibility", vis3);
}, 3000);
}, 3000);
Thanks,
Areeb
I suggest you give your elements a common class, ex:
<div class="blink">One</div>
<div class="blink">Two</div>
<div class="blink">Three</div>
Then you can simplify your code to:
//Cache element collection and keep a reference to the visible element
var $elements = $('.blink').css('visibility','hidden'),
$visible = $elements.first().css('visibility','visible');
//Single interval function to handle blinking
setInterval(function(){
//Hide visible element
$visible.css('visibility','hidden');
//Find next one
var $next = $visible.next('.blink');
if(!$next.length)
$next = $elements.first();
//Show next element
$visible = $next.css('visibility','visible');
},1000);
Demo fiddle
This may be what you're looking for. http://jsfiddle.net/andaywells/eQuXn/15/
I have modified this code: http://jsfiddle.net/paislee/pdsu7/5/
So that each div stays in position, the 'hold' div keeps it there.
$(document).ready(function () {
var delay = 5000,
fade = 500;
var banners = $('.banner');
var len = banners.length;
var i = 0;
setTimeout(cycle, delay);
function cycle() {
$(banners[i % len]).fadeOut(fade, function () {
$(banners[++i % len]).fadeIn(fade, function () {
setTimeout(cycle, delay);
});
});
}
});
Perhaps this example will help you.
CSS
.lamp {
height: 30px;
width: 30px;
border-style: solid;
border-width: 2px;
}
.lampRed {
background-color: red;
}
.lampYellow {
background-color: yellow;
}
.lampGreen {
background-color: green;
}
HTML
<div id="trafficLight">
<div>Click to Start and Stop</div>
<div class="lamp" id="Red"></div>
<div class="lamp" id="Yellow"></div>
<div class="lamp" id="Green"></div>
</div>
Javascript
var changeState = (function () {
var state = 0,
lamps = ["Red", "Yellow", "Green"],
lampsLength = lamps.length,
order = [
[5000, "Red"],
[3000, "Red", "Yellow"],
[5000, "Green"],
[3000, "Yellow"]
],
orderLength = order.length,
lampIndex,
orderIndex,
sId;
return function (stop) {
if (stop) {
clearTimeout(sId);
return;
}
var lamp,
lampDOM;
for (lampIndex = 0; lampIndex < lampsLength; lampIndex += 1) {
lamp = lamps[lampIndex];
lampDOM = document.getElementById(lamp);
if (order[state].indexOf(lamp) !== -1) {
lampDOM.classList.add("lamp" + lamp);
} else {
lampDOM.classList.remove("lamp" + lamp);
}
}
sId = setTimeout(changeState, order[state][0]);
state += 1;
if (state >= orderLength) {
state = 0;
}
};
}());
document.getElementById("trafficLight").addEventListener("click", (function () {
var state = false;
return function () {
changeState(state);
state = !state;
};
}()), false);
On jsfiddle

Categories