Add CSS only when a section or is in range - javascript

I am trying to make a "sticky" image where all images of class ".img" add a css attribute and then remove it when it is not in range.
I do this by getting the ID of each of the images and pass it to a function that makes it fixed (addCSS). It works fine - the images stick right where they are supposed to smoothly, but when I try to scroll up, they keep their css. I want to remove the CSS property when the wScroll is outside the range.
$('.img').each(function () {
var sectionOffset = $(this).offset().top;
var attID = $(this).attr('id');attID = $("#"+attID.toString()+"");
if (wScroll >= sectionOffset && wScroll <= (sectionOffset + sectionHeight)) {
addCSS(attID);
}
});
function addCSS(element) {
element.css({
'position': 'fixed',
'top': stickyPosition - 75,
'left': OffsetLeft
});
}
function removeCSS(element) {
element.css({
'position': '',
'top': '',
'left': ''
});
}
I tried modifying it this way but it makes it jump :(
$('.img').each(function () {
var sectionOffset = $(this).offset().top;
var attID = $(this).attr('id');attID = $("#"+attID.toString()+"");
if (wScroll >= sectionOffset && wScroll <= (sectionOffset + sectionHeight)) {
addCSS(attID);
}
else if (wScroll > (sectionOffset + sectionHeight) || wScroll < sectionOffset) {
removeCSS(attID);
}
});
I managed to get it working smoothly without using an array, but the code is a bit long and I was hoping to simplify it without losing function.
Here is a simplified version: http://codepen.io/ebevers/pen/xwbdbP
for this, I just need the squares to jump back into place. Thanks!

Try this:
// Last section and current section
var last_section = -1;
var current_section = -1;
// Scroll
jQuery(window).scroll(function(){
// Get current section
for (var i = 0; i < jQuery('.row').length; i++) {
if (jQuery(this).scrollTop() >= jQuery('.row:eq('+i+')').position().top) {
current_section = i;
}
}
// If change
if (current_section != last_section) {
removeCSS(jQuery('.row:eq('+last_section+') .img'));
addCSS(jQuery('.row:eq('+current_section+') .img'));
last_section = current_section;
}
});
http://jsfiddle.net/c4z9satw/

Another way of doing it, but without globals and it relies on explicitly set identifiers.
Added CSS:
.active {
position: fixed;
top: 100px;
left: 100px;
}
JavaScript:
$(window).scroll(function() {
var rows = $(".row");
$(".img").each(function() {
var row = false, i, l, id;
for (i = 0, l = rows.length; i < l; i++) {
id = "#" + this.id.toString();
if ($(rows[i]).find(id)[0] != undefined) {
row = rows[i];
break;
}
}
if (!row)
return false;
if ((window.scrollY >= $(row).offset().top) && (window.scrollY < $(row).offset().top + $(row).outerHeight()))
$(this).addClass("active");
else
$(this).removeClass("active");
});
});
JSFiddle: http://jsfiddle.net/w7ru130s/2/

Related

Sticky Edge - getting the edge of a cell, inside a carousel

I am working on an application that has a custom carousel and there is a desirable to intuitively move the inner contents of an item so its always in view until the item is truly out of scope.
^ so as the .item is moved in the left position. What techniques would you use to detect the edge to dynamically position the .unit padding-left value? So the text inside that cell is always viewable, even if the item starts to move out of position.
//Latest Fiddle
https://jsfiddle.net/atg5m6ym/3124/
$(document).ready(function() {
//console.log("ready!");
function isElementInViewport (el) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
var currentPadding = 0;
var newPadd = 0;
function compensatePadding() {
var itemLeft = Math.abs(parseInt($('.caroseul').offset().left));
console.log("itemLeft", itemLeft)
newPadd = Math.abs(itemLeft);
$('.stick .unit').css("padding-left", newPadd + "px");
}
var unitWidth = $('.unit').width();
console.log("unitWidth", unitWidth);
function onVisibilityChange(el, callback) {
var old_visible;
return function() {
var visible = isElementInViewport(el);
if (visible != old_visible) {
old_visible = visible;
if (typeof callback == 'function') {
callback();
}
}
}
}
function checkVisible() {
console.log("checkvisible");
var labelGroups = $('.caroseul .item .wraps');
var length = labelGroups.length;
for (i = 0; i < length; i++) {
var isItemLabelInView = isElementInViewport(labelGroups[i]);
if(!isItemLabelInView){
$(labelGroups[i]).closest(".item").addClass("stick");
}
else{
$(labelGroups[i]).closest(".item").removeClass("stick");
//reset moved items
$('.unit').css("padding-left", 0);
}
console.log(" labelGroups[i]", labelGroups[i]);
console.log("isItemLabelInView", isItemLabelInView);
}
compensatePadding();
}
$('.container').on('scroll', checkVisible);
});
I tweaked a bit of your code - instead of checking if label is in viewport or not I have checked if label is moving out of viewport from left.
if ($(labelGroups[i]).offset().left < 0) {
$(labelGroups[i]).closest(".item").addClass("stick");
} else {
$(labelGroups[i]).closest(".item").removeClass("stick");
Besides this I have added a few conditions and offset values in compensatePadding() function.
Please refer this fiddle.
Using jquery for this pains me a bit, as I think you'd be better off using requestAnimationFrame...but, to answer your specific question, you could use something like this (I've specifically left the two aggregate values as separate vars in order to explain the point):
$(document).ready(function() {
function animateMe(){
$(".item").animate({
left: "-=5"
}, 1000, function() {
amountMovedLeft += 5;
if(amountMovedLeft >= amountUntilUnitHitsLeft){
$(".unit").animate({
right: "+=5"
}
}
});
}
var amountMovedLeft = 0;
var unitWidthHalf = $('.unit').width()/2;
var itemWidthHalf = $('.item').width()/2;
var amountUntilUnitHitsLeft = itemWidthHalf - unitWidthHalf;
setInterval(function(){
animateMe();
}, 1000);
});

jQuery slider doesn't rotate

I have a slider rotator on my site but it doesn't rotate items automatically in the boxes - navigation works and rotate but I want it to rotate automatically, right after I enter the site.
This is my js:
$(document).ready(function() {
var nbr = 0;
$('.slider').each(function() {
var slider = $(this);
//get width and height of the wrapper and give it to the UL
var wrapperwidth = $(slider).width() * $(slider).find('ul > li').size();
$(slider).find('ul').css('width', wrapperwidth);
var wrapperheight = $(slider).height();
$(slider).find('ul').css('height', wrapperheight);
//set my li width
var width = $(slider).width();
$(slider).find('ul li').css('width', width);
//set my counter vars
var counter = $(slider).find('ul > li').size();
var decount = 1;
var autocount = 1;
if (counter > 1) {
//create my number navigation
var createNum = 1;
$(slider).after('<ul class="numbers"><li></li></ul>');
var numbers = $(slider).parent().find('.numbers');
$(numbers).find('li:first-child').html(createNum+'_'+nbr).addClass('activenum').attr('id', 'id1_'+nbr);
while ( createNum != counter) {
createNum++;
$(numbers).append("<li id='id"+createNum+"_"+nbr+"'>"+createNum+"_"+nbr+"</li>");
}
//get my number-width (number navigation should always be centered)
var numwidth = $(slider).find('.numbers li:first-child').width() * $(slider).find('.numbers li').size();
$(slider).find('.numbers').css('width', numwidth);
}
nbr++;
});
//make the number clickable
$(".numbers li").click(function() {
var slider = $(this).closest('.sliderWrapper');
var slider0 = $(slider).find('.slider');
var clickednum = $(this).html().split('_')[0] * - $(slider0).width() + $(slider0).width();
$(slider0).find('ul').animate({ left: clickednum }, 400, 'swing', function() { });
$(slider).find('.activenum').removeClass('activenum');
$(this).addClass('activenum');
decount = $(this).html();
});
rotateSwitch = function(sliderW, speed) {
var sliderWrap = sliderW;
play = setInterval(function() {
var nextNum = parseInt($($(sliderWrap).find(".numbers li.activenum")).html().split('_')[0])+1;
if (nextNum > $(sliderWrap).find(".numbers li").length) {
nextNum = 1;
}
//console.log("nextnum: "+nextNum+", numbers length: "+$(sliderWrap).find(".numbers li").length);
$(sliderWrap).find(".numbers li").each(function() {
if( parseInt($(this).html().split('_')[0]) == nextNum )
$(this).click();
});
}, speed);
};
makeAutoSlide = function(sliderWrap, speed) {
if ($(sliderWrap).length > 0 && $(sliderWrap).find(".numbers li").length > 1) {
rotateSwitch(sliderWrap, speed);
$(sliderWrap).find(".slider li").hover(function() {
if ($(sliderWrap).find(".numbers li").length > 1) {
clearInterval(play); //Stop the rotation
}
}, function() {
if ($(sliderWrap).find(".numbers li").length > 1) {
rotateSwitch(sliderWrap, speed); //Resume rotation timer
}
});
}
};
});
I'm not really sure if this is a problem with setInterval and clearInterval or I wrote something wrong.
I put code in jsFiddle, so you know how the structure looks like.
http://jsfiddle.net/gecbjerd/1/
I appreciate for help.
Cheers

DIV animation and property change

I'm trying to simulate TCP packet transmission and sliding window, and fortunately I've made much progress. But now I want to fix a minor issue with the sliding window, which is a sliding DIV:
Hopefully if you are familiar with TCP's slow start, the window size double up to a number, and then increments by one. This is working. Now what I want to fix is sliding to right. So I want to automatically slide one step right when each ack is received at the original machine. Currently it does not move when the ack is received; so each time I press the button, it retransmits many of the previous packets! My work is here: http://web.engr.illinois.edu/~shossen2/CS438/Project/
$(document).ready(function () {
var count = 0;
var items = 0;
var packetNumber = 0;
var speed = 0;
var ssth= $("#ssth").val();
var window_left=0;
for (var i = 1; i <= 32; i++) {
$('#table').append("<div class='inline' id='"+i+"'>"+i+"</div>");
}
document.getElementById(1).style.width = 22;
$("button").click(function() {
if (items < ssth) {
if (items == 0)
items = 1;
else
items = items * 2;
count++;
} else {
items = items + 1;
}
window_left += 20;
window_width=items * 20;
document.getElementById("window_size").innerHTML = items;
document.getElementById("window").style.left= window_left + "px";
document.getElementById("window").style.width=window_width + "px";
speed = +$("#speed").val();
createDivs(items);
animateDivs();
});
function createDivs(divs) {
packetNumber = 1;
var left = 60;
for (var i = 0; i < divs; i++) {
var div = $("<div class='t'></div>");
div.appendTo(".packets");
$("<font class='span'>" + (parseInt(packetNumber) + parseInt(window_left/20) -1) + "</font>").appendTo(div);
packetNumber++;
div.css({
left: left
/* opacity: 0*/
}).fadeOut(0);
//div.hide();
//left += 20;
}
}
function animateDivs() {
$(".t").each(function (index) { // added the index parameter
var packet = $(this);
packet
.delay(index * 200)
.fadeIn(200, function() {
$('#table #' + (index + window_left/20)).css({background:'yellow'});
})
.animate({left: '+=230px'}, speed)
.animate({left: '+=230px'}, speed)
.fadeOut(200, function () {
packet
.css({
top: '+=20px',
backgroundColor: "#f09090"
})
.text('a' + packet.text());
})
.delay(500)
.fadeIn(200)
.animate({left:'-=230px'}, speed)
.animate({left:'-=230px'}, speed)
.fadeOut(200, function () {
packet
.css({
top: '-=20px',
backgroundColor: "#90f090"
});
$('#table #' + (index + window_left/20)).css({background:'lightgreen'});
});
}).promise().done(function(){
$(".packets").empty();
});
}
});

Transition List Item Scrolling - HTML

Here's the FIDDLE.
List item that appears on clicking the up and down arrows.
When I click on it. It appears instantly which I don't want it to be like that.
I wanted to add a transition to it but I don't have any clue whether to apply it on a li or a tag.
Besides I'm here hiding and revealing li items on click. But I need the transition like when I click on the up arrow, I want the hidden element to push the active element downwards and vice versa.
Someone help me in this.
I updated your FIDDLE
you may check it out.
var
cur = 2,
$container = $('.dropdown-container'),
$ul = $('.dropdown'),
$ul_length = $('.dropdown li').children().length,
$up = $('.up'),
$down = $('.down'),
changeLi = function (cur) {
var $cur_li = $('.dropdown li:nth-child(' + cur + ')');
$('.current_selected').removeClass('current_selected');
$cur_li.addClass('current_selected');
$container
.height($cur_li.outerHeight())
.width($cur_li.outerWidth());
$up.offset({
left: ($container.outerWidth() - $up.outerWidth()) / 2
});
$down.offset({
left: ($container.outerWidth() - $down.outerWidth()) / 2
});
$ul.animate({
top: -$cur_li.position().top
}, 200);
};
$up.on('click', function () {
cur--;
if (cur < 1) {
cur = 1;
return false;
}
changeLi(cur);
});
$down.on('click', function () {
cur++;
if (cur > $ul_length) {
cur = $ul_length;
return false;
}
changeLi(cur);
});
changeLi(cur);
You can add animatation like slideUp, slideDown etc.
var cur = 2;
$('.up').click(function() {
if(cur <= 0) return;
var last = cur;
cur --;
$('.dropdown li').eq(last).hide(500).addClass('hide');
$('.dropdown li').eq(cur).show(100).removeClass('hide');
});
$('.down').click(function() {
if(cur >= $('.dropdown li').length - 1) return;
var last = cur;
cur ++;
$('.dropdown li').eq(last).hide(500).addClass('hide');
$('.dropdown li').eq(cur).show(100).removeClass('hide');
});

.next() not working as intended

So,
if($(this).hasClass('active')){
$(this).removeClass('active');
$(this).prev().addClass('active');
}
works fine, it adds the class "active" to this previous div of the same kind.
if($(this).hasClass('active')){
$(this).removeClass('active');
$(this).next().addClass('active');
}
However, adds the class to the next div (as i intend for it to do) for about 0.5 of a second BUT then removes it.
Here's ALL of the jQuery (as per your comments below) - Please do not comment on my horrible code organization
$(window).load(function () {
// Initial variables
var numberSlides = 0;
var currentSlide = 1;
var ready = true;
var pageWidthR = $(document).width() - 352;
var pageWidthL = $(document).width() - 352;
// Update number of slides by number of .slide elements
$('#features-slider .slide').each(function () {
numberSlides++;
});
// Go through each slide and move it to the left of the screen
var i = 0;
$($('#features-slider .slide').get().reverse()).each(function () {
if (i == 0) {
} else {
var newWidth = i * 115;
$(this).css('left', '-' + newWidth + '%');
}
i++;
});
// Animate the first slide in
$('#features-slider .slide:last-child').addClass('active').animate({
left: 0
}, 1500);
// Remove the loading message
$('#loading').fadeOut(1000, function () {
$('#loading').remove();
// Now that we're done - we can show it
$('#features-slider').show();
});
/***** Left and Right buttons *****/
/* Right */
$('#rightbutton').click(function () {
var numberSlides = 0;
$('#features-slider .slide').each(function () {
numberSlides++;
});
var index = $('.slide.active').index() + 1;
if (!$('.slide').is(':animated') && index != 1) {
$('#features-slider .slide').each(function () {
if ($(this).hasClass('active')) {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) + 115;
} else {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) + 115;
}
$(this).animate({
left: newLeft + '%'
}, 1500);
if ($(this).hasClass('active')) {
$(this).removeClass('active');
$(this).prev().addClass('active');
}
});
}
});
/* Left */
$('#leftbutton').click(function () {
var numberSlides = 0;
$('#features-slider .slide').each(function () {
numberSlides++;
});
var index = $('.slide.active').index() + 1;
if (!$('.slide').is(':animated') && index != numberSlides) {
$('#features-slider .slide').each(function () {
if ($(this).hasClass('active')) {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) - 115;
} else {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) - 115;
}
$(this).animate({
left: newLeft + '%'
}, 1500);
if ($(this).hasClass('active')) {
$(this).next().addClass('active');
$(this).removeClass('active').not($(this).next());
}
});
}
});
});
$(document).ready(function () {
// Hide the slider and show a loading message while we do stuff and the images / DOM loads - Also disable overflow on the body so no horizontal scrollbar is shown
$('body').css('overflow-x', 'hidden');
$('#features-slider').hide();
$('#loading').html('<center> <img id="loader" src="/wp-content/themes/responsive/library/images/ajax-loader.gif" /> Loading</center>');
});
RESOLVED
New left button function :
$('#leftbutton').click(function(){
var numberSlides = 0;
$('#features-slider .slide').each(function(){
numberSlides++;
});
var index = $('.slide.active').index()+1;
if( !$('.slide').is(':animated') && index != numberSlides ){
var done = false;
$('#features-slider .slide').each(function(){
if($(this).hasClass('active')){
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft)-115;
} else {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft)-115;
}
$(this).animate({left: newLeft+'%'}, 1500);
if($(this).hasClass('active') && done == false){
$(this).next().addClass('active');
$(this).removeClass('active');
done = true;
}
});
});
If you're iterating forward through the elements, then it should be clear what's going on - you add the "active" class to the next element, and then the next iteration takes it away.
This is just a guess however as you did not post enough code for me (or anybody else) to be sure.
edit — ok now that you've updated the question, it's clear that the guess was correct. The .each() function will iterate forward through the elements. When an element has the "active" class, and the code removes it and adds it to the next element, then on the next iteration the work is undone.
Since you are referencing this and by the behavior you're describing, you are likely iterating a loop for a list of elements. As a result, you are completing the action you want but the next iteration is removing the previous changes due to your usage of removing a class and then adding the class back.
As it stands now, your code does not illustrate how this occurence can be happening.
Update:
As suspected, you seem to be looping as signified by: each(function(){. While iterating through your objects the class is being pushed forward and is not acting as desired. You are stating add the class to the next element, but remove it from the current element, and this behavior continues through your iteration.
On a side note, update your code to call removeClass() on the current object first, before adding it to the next object:
if ($(this).hasClass('active')) {
$(this).removeClass('active').next().addClass('active');
}

Categories