Slide HTML Table rows up and repeate - javascript

I found some cool code while working on a project. Its jquery that effects a html table. It basically makes the tbody scroll up so the row that was at the top goes to the bottom and the rest of the rows shift up. This is what I mean:
<tr><td>1a</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
<tr><td>1b</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
<tr><td>1c</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
<tr><td>1d</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
becomes:
<tr><td>1b</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
<tr><td>1c</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
<tr><td>1d</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
<tr><td>1a</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
Row 1a moves to the bottom. This is the jquery code I am using:
<script type="text/javascript">
$.fn.infiniteScrollUp=function(){
var self=this,kids=self.children()
kids.slice(20).hide()
setInterval(function(){
kids.filter(':hidden').eq(0).fadeIn()
kids.eq(0).fadeOut(function(){
$(this).appendTo(self)
kids=self.children()
})
},5000)
return this
}
$(function(){
$('tbody').infiniteScrollUp()
})
</script>
This works fine. No problems. How ever when I tried to make it so it just slides up, just like a reel of some sort, it either 1) stops adding it to the bottom, 2) stops removing them from the top, or 3) nothing. How can I change this effect to slide up?
Here is the jsfiddle example.

Sliding tr elements up/down is tricky. They don't behave like block elements.
This is the best I can manage :
$.fn.infiniteScrollUp = function() {
var self = this;
var kids = self.children();
kids.children('td, th').wrapInner('<div class="dummy"/>')
setInterval(function() {
var first = kids.eq(0),
clone = first.clone().appendTo(self);
first.find(".dummy").slideUp(1000, function() {
kids = kids.not(first).add(clone);
first.remove();
});
}, 2000);
return this;
};
Updated fiddle

I'm not sure about the plugin you have added above but here is another quick way around it that works as you have described, a little bit simpler in my opinion. There may be better ways around it.
function moveRows(){
firstTR = $('tbody tr').first();
firstTR.animate({opacity:0},
function(){$('tbody').append(firstTR);});
firstTR.animate({opacity:1});
}
setInterval(function(){
moveRows();
},1000);
And here is a Fiddle example.

Related

Replacing Bootstrap Dropdown with Dropup (Different activity on two near identical implementations)

I'm working on a project over at github pages, which I replace a bootstrap .dropdown with .dropup if the div's overflow-y: scroll will cause the dropdown menu to be cutoff / overflow. You can see the function working properly at this jsfiddle. Notice if you click on the ellipsis icon to the right on the top rows, it will drop down, if you click on the icon on the bottom rows, it will drop up.
Now, my actual implementation (github page), the code is exactly the same (below), but it wants to replace all .dropdown classes with .dropup when opened, including the top-most row which gets cut off, seen in the photo below.
I've been struggling with this for a week and can't quite figure it out. I've tried a few different things that I thought fixed it but ended up just being a hack and didn't work on mobile, or replaced some but not all etc.
Here is the Javascript / jQuery I'm using, which can be seen in the jsfiddle and my github source here.
$(document).on("shown.bs.dropdown", ".dropdown", function () {
// calculate the required sizes, spaces
var $ul = $(this).children(".dropdown-menu");
var $button = $(this).children(".song-menu");
var ulOffset = $ul.offset();
// how much space would be left on the top if the dropdown opened that direction
var spaceUp = (ulOffset.top - $button.height() - $ul.height()) - $('#playlist').scrollTop();
// how much space is left at the bottom
var spaceDown = $('#playlist').scrollTop() + $('#playlist').height() - ((ulOffset.top + 10) + $ul.height());
// switch to dropup only if there is no space at the bottom AND there is space at the top, or there isn't either but it would be still better fit
if (spaceDown < 0 && (spaceUp >= 0 || spaceUp > spaceDown))
$(this).addClass("dropup");
}).on("hidden.bs.dropdown", ".dropdown", function() {
// always reset after close
$(this).removeClass("dropup");
});
Edit:
To clear up any confusion, here's an example of the behavior without my added .dropup function. jsfiddle Notice when you click the last menu item, it opens the menu but requires scrolling. I specifically want to remove the .dropdown class and add .dropup in this case, so no scrolling is required.
It took some basic math, but I managed to figure out what you desired to do. This code changes the bootstrap classes between dropup and dropdown depending on the room available for a normal dropdown.
I calculated this by detracting the height of the button, dropdownmenu and how far the button was scrolled down in the scrollContainer from the height of the scrollContainer. I got the value how much the div was scrolled down by using the buttons offset and detracting the offset from the scrollContainer.
Here is my jQuery (I selected the .playlist class because this was attached to your scrollContainer, but you should replace it by an id or select it by other means):
$(".dropdown, .dropup").click(function(){
var dropdownClassCheck = $(this).hasClass('dropdown');
var buttonOffset = $(this).offset().top;
var scrollboxOffset = $('.playlist').offset().top;
var buttonHeight = $(this).height();
var scrollBoxHeight = $('.playlist').height();
var dropDownButtonHeight = $(this).children('ul').height();
dropdownSpaceCheck = scrollBoxHeight>buttonOffset-scrollboxOffset+buttonHeight+dropDownButtonHeight;
if(dropdownClassCheck && !dropdownSpaceCheck){
$(this).removeClass('dropdown').addClass('dropup');
}
else if(!dropdownClassCheck && dropdownSpaceCheck){
$(this).removeClass('dropup').addClass('dropdown');
}
});
A working JSFiddle
Let me know if there are parts of the code that could be improved/done easier or if there are any problems with my solution.
I have not thoroughly checked, but .scrollTop() is probably why the code fails when combined with other elements in the DOM, so here is a solution without it:
function checkHeights(){
// LOOP through each dropdown
$('.dropdown,.dropup').each(function(index,element){
var $dropDown = $(element),
$dropDownMenu = $dropDown.find('.dropdown-menu'),
dropDownTop = $dropDown.offset().top,
visibleHeight = $dropDown.height(),
hiddenHeight = $dropDownMenu.height(),
ddTop = dropDownTop - hiddenHeight,
ddBottom = dropDownTop + visibleHeight + hiddenHeight;
// LOOP through all parents
$dropDown.parents().each(function(ix,el){
var $el = $(el);
// CHECK if any of them have overflow property set
if( $el.css('overflow') !== 'visible' ){
var limitTop = $el.offset().top,
limitBottom = limitTop + $el.height();
// CHECK if parent is better fit when dropped upside
if( limitBottom < ddBottom && ( ddTop - limitTop ) > ( limitBottom - ddBottom ) )
$dropDown.removeClass('dropdown').addClass('dropup');
else
$dropDown.removeClass('dropup').addClass('dropdown');
// BREAK LOOP
return false;
}
});
});
}
$(document).ready(function() {
checkHeights();
$('.playlist').scroll(checkHeights);
});
JS Fiddle here.
This one does not require any class or id given to it except for dropdown,dropdown-menu, and dropup (all of which are Bootstrap defaults) and would work fine even if there are multiple playlists on page.
UPDATE
The code is modified and wrapped in a function in order to allow being called when scroll event fires.
I think that the problem it's that you have a big header, and the jsFiddle don't. So ulOffset.top it's always big, and spaceDown is always negative
Replace parent div.dropdown with div.dropup.

Previous and Next Scrolling to next post

I've been struggling with this all day.. I've got a couple of posts, each have a next and previous button. The idea is for each post and its next and previous buttons, to scroll the window to the next post or previous post. I have tried using the each() function and unfortunately, its tricky to get working.
This is the jQuery so far:
var scrollTo = function(element) {
$('html, body').animate({
scrollTop: element.offset().top
}, 100);
}
function prev_next_scrolling() {
var articles = $("article.post"),
counter = 0;
articles.each( function() {
var articles = $(this);
$('.next-btn', articles).click( function() {
scrollTo($('article.post').eq(counter + 1));
});
$('.prev-btn', articles).click( function() {
scrollTo($('article.post').eq(counter - 1));
});
counter++;
});
}
prev_next_scrolling();
And this is the HTML:
<article class="post">
<h2>Post Title</h2>
<p>Post description</p>
Previous
Next
</article>
Here is the jsfiddle link for you guys to have a looksie!
http://jsfiddle.net/casacoda/2zM3Q/
Any help will be much appreciated! Thanks in advance guys!
The problem with your code is that counter is defined in the scope of prev_next_scrolling(), so all the functions run by the each() method will use the very same instance of the variable. Each time you increase counter, that will happen for all places where it has been used.
You can fix that by introducing a variable local to the function that handles a specific element -- or actually, you don't have to because jQuery already gives you exacly that as an optional parameter in the each() callable. See http://api.jquery.com/each/
So here's the correct code (http://jsfiddle.net/2zM3Q/3/):
var scrollTo = function(element) {
$('html, body').animate({
scrollTop: element.offset().top
}, 100);
}
function prev_next_scrolling() {
var articles = $("article.post"),
counter = 0;
articles.each( function(index) {
var articles = $(this);
$('.next-btn', articles).click( function() {
scrollTo($('article.post').eq(index + 1));
});
$('.prev-btn', articles).click( function() {
scrollTo($('article.post').eq(index - 1));
});
counter++;
});
}
prev_next_scrolling();
There are still some problems: It doesn't check whether it already is the first/last post and if it's already at the end of the page it obviously won't scroll any further, creating the illusion of a "broken" link (because nothing seems to be happening after clicking it.)
I've updated the fiddle to address all your concerns in the comments
Updated Working Fiddle
I got it working without all your each code, just navigating the dom.
Let me know if you have questions about the Fiddle provided. Basically this takes advantage of your current structure being known, it finds the next ARTICLE using parent().next() and then finds that ARTICLEs h2. It then uses the H2s vertical offset position to scroll to it. Same for previous links but using parent().prev()
$(document).on('click', '.next-btn', function(){
// find the next anchor
var nextAnchor = $(this).closest('article').next().find('h2')
$('html,body').animate({scrollTop: nextAnchor.offset().top},'slow');
});
$(document).on('click', '.prev-btn', function(){
// find the previous anchor
var prevAnchor = $(this).closest('article').prev().find('h2')
$('html,body').animate({scrollTop: prevAnchor.offset().top},'slow');
});
One thing to note, if the H2 in question is already visible on the screen it will not scroll UP to anything, only if its off screen will it scroll UP to it. Scroll down will always move the screen if needed.

Jquery click function inside each loop

When I click .zoom in this example, I inject 20 (the amount of items in the loop) .big_image divs. I'd just like to insert one, relative to the item I am clicking.
$('.main img').each(function() {
var img = this;
$('.zoom').click(function() {
$(this).after('<div class="big_image"><img src="'+$(img).attr('src')+'"></div>');
});
});
I have simplified the script right down here. Ideally I'd just like to know how to modify the click function (if possible) as there are other things going on not related to the question. Thanks!
EDIT: Working example here.
The zoom button should appear on at least the first 2 images in the gallery (top left corner). If it's confusing, I'm trying to get the zoom button to only appear on very long/tall images. I'm also aware that I should split the setClass function up but haven't learned how to do that yet :)
$('.zoom').click(function(e){
var imgURL= $(this).parents('.main').find('img').attr('src');
$(this).after('<div class="big_image"><img src="'+imgURL+'"></div>')
});
if .main container is the immediate parent of both the img and .zoom you can use
var imgURL= $(this).siblings('img').attr('src');
if it HAS to be inside the loop. try modifying your code like below
var flag=false;
$('.main img').each(function() {
var img = this;
$('.zoom').click(function() {
if(!flag)
$(this).after('<div class="big_image"><img src="'+$(img).attr('src')+'"></div>');
flag=true;
});
});
The person who answered this removed their answer for some reason! The key is .next()
var img = this;
$(this).next('.zoom').click(function() {
$(this).after('<div class="big_image"><img src="'+$(img).attr('src')+'"></div>');
});

Scrolling to Div IDs with Jquery

Due to css properties my scrolling to div tags has too much margin-top. So I see jquery as the best solution to get this fixed.
I'm not sure why this isn't working, I'm very new to Js and Jquery. Any help us greatly appreciated.
Here is a quick look at Js. I found that when your div ids are in containers to change the ('html, body') to ('container)
Here is my jsfiddle
jQuery(document).ready(function($){
var prevScrollTop = 0;
var $scrollDiv = jQuery('div#container');
var $currentDiv = $scrollDiv.children('div:first-child');
var $sectionid = 1;
var $numsections = 5;
$scrollDiv.scroll(function(eventObj)
{
var curScrollTop = $scrollDiv.scrollTop();
if (prevScrollTop < curScrollTop)
{
// Scrolling down:
if ($sectionid+1 > $numsections) {
console.log("End Panel Reached");
}
else {
$currentDiv = $currentDiv.next().scrollTo();
console.log("down");
console.log($currentDiv);
$sectionid=$sectionid+1;
console.log($currentDiv.attr('id'));
var divid =$currentDiv.attr('id');
jQuery('#container').animate({scrollTop:jQuery('#'+divid).position().top}, 'slow');
}
}
else if (prevScrollTop > curScrollTop)
{
// Scrolling up:
if ($sectionid-1 == 0) {
console.log("Top Panel Reached");
}
else {
$currentDiv = $currentDiv.prev().scrollTo();
console.log("up");
console.log($currentDiv);
$sectionid=$sectionid-1;
var divid =$currentDiv.attr('id');
jQuery('html, body').animate({scrollTop:jQuery('#'+divid).position().top}, 'slow');
}
}
prevScrollTop = curScrollTop;
});
});
I'm not entirely sure what you want but scrolling to a <div> with jQuery is simpler than your code.
For example this code replaces the automatic jumping behaviour of anchors with smoother scrolling:
$(document).ready(function(e){
$('.side-nav').on('click', 'a', function (e) {
var $this = $(this);
var top = $($this.attr('href')).offset().top;
$('html, body').stop().animate({
scrollTop: top
}, 'slow');
e.preventDefault();
});
});
You can of course adjust the top variable by adding or removing from it like:
var top = $($this.attr('href')).offset().top - 10;
I have also made a fiddle from it (on top of your HTML): http://jsfiddle.net/Qn5hG/8/
If this doesn't help you or your question is something different, please clarify it!
EDIT:
Problems with your fiddle:
jQuery is not referenced
You don't need jQuery(document).ready() if the jQuery framework is selected with "onLoad". Remove the first and last line of your JavaScript.
There is no div#container in your HTML so it's no reason to check where it is scrolled. And the scroll event will never fire on it.
Your HTML is invalid. There are a lot of unclosed elements and random tags at the end. Make sure it's valid.
It's very hard to figure out what your fiddle is supposed to do.

Jquery - Carasol build finished and would like advice on best practice / neatening up my code

I have been building my own carasol over the past few days.
My Jquery is based on tutorials on the web and also from help and advice from SO.
I am not a Jquery guru just an enthusiast and think my code is a little sloppy, hence the post.
here is a link to the working code: http://jsfiddle.net/JHqBA/2/ (updated link)
basically what happens is:
if someone hits the page with a # values in the url it will show the appropriate slide and example would be www.hello.com#two, this would slide to slide two
if someone clicks the numbers it will show the appropriate slide
next and prev also slide through the slides.
The question is, is there anything i could have wrote better as i know there is alot of duplicate code.
I understand its a big ask but it would help me learn a little more (i think my code is a little old school)
if anyone has any questions please feel free to ask and ill answer what it does or is supposed to do.
Sluap
--- Edit ----
I have made only one aniamtion function now which has got rid of alot of duplicate code.
I have yet to look into on function but will do soon.
I would like to know more about the create a new function, outside of the jQuery ready block as i cant get this working or quite understand how i can get it to work sorry
any more tips would be great ill carry on working on this project till i am happy with it.
also is there a better way to write:
if ($slideNumber == 1) {
$('#prev').attr("class", "not_active")
$('#next').attr("class", "active")
}
else if ($slideNumber == divSum) {
$('#next').attr("class", "not_active");
$('#prev').attr("class", "active");
}
else {
$('#prev').attr("class", "active")
$('#next').attr("class", "active")
};
Jquery full:
$(document).ready(function () {
//////////////////////////// INITAL SET UP /////////////////////////////////////////////
//Get size of images, how many there are, then determin the size of the image reel.
var divWidth = $(".window").width();
var divSum = $(".slide").size();
var divReelWidth = divWidth * divSum;
//Adjust the image reel to its new size
$(".image_reel").css({ 'width': divReelWidth });
//set the initial not active state
$('#prev').attr("class", "not_active");
//////////////////////////// SLIDER /////////////////////////////////////////////
//Paging + Slider Function
rotate = function () {
var triggerID = $slideNumber - 1; //Get number of times to slide
var image_reelPosition = triggerID * divWidth; //Determines the distance the image reel needs to slide
//sets the active on the next and prev
if ($slideNumber == 1) {
$('#prev').attr("class", "not_active")
$('#next').attr("class", "active")
}
else if ($slideNumber == divSum) {
$('#next').attr("class", "not_active");
$('#prev').attr("class", "active");
}
else {
$('#prev').attr("class", "active")
$('#next').attr("class", "active")
};
//Slider Animation
$(".image_reel").animate({
left: -image_reelPosition
}, 500);
};
//////////////////////////// SLIDER CALLS /////////////////////////////////////////////
//click on numbers
$(".paging a").click(function () {
$active = $(this); //Activate the clicked paging
$slideNumber = $active.attr("rel");
rotate(); //Trigger rotation immediately
return false; //Prevent browser jump to link anchor
});
//click on next button
$('#next').click(function () {
if (!$(".image_reel").is(':animated')) { //prevent clicking if animating
var left_indent = parseInt($('.image_reel').css('left')) - divWidth;
var slideNumberOn = (left_indent / divWidth);
var slideNumber = ((slideNumberOn * -1) + 1);
$slideNumber = slideNumber;
if ($slideNumber <= divSum) { //do not animate if on last slide
rotate(); //Trigger rotation immediately
};
return false; //Prevent browser jump to link anchor
}
});
//click on prev button
$('#prev').click(function () {
if (!$(".image_reel").is(':animated')) { //prevent clicking if animating
var left_indent = parseInt($('.image_reel').css('left')) - divWidth;
var slideNumberOn = (left_indent / divWidth);
var slideNumber = ((slideNumberOn * -1) - 1);
$slideNumber = slideNumber;
if ($slideNumber >= 1) { //do not animate if on first slide
rotate(); //Trigger rotation immediately
};
}
return false; //Prevent browser jump to link anchor
});
//URL eg:www.hello.com#one
var hash = window.location.hash;
var map = {
one: 1,
two: 2,
three: 3,
four: 4
};
var hashValue = map[hash.substring(1)];
//animate if hashValue is not null
if (hashValue != null) {
$slideNumber = hashValue;
rotate(); //Trigger rotation immediately
return false; //Prevent browser jump to link anchor
};
});
Question and answer has been moved over to https://codereview.stackexchange.com/questions/8634/jquery-carasol-build-finished-and-would-like-advice-on-best-practice-neateni/8635#8635
1) Separation of Concerns
Start by refactorring your code in to more granular functions.
You can read more about SoF at http://en.wikipedia.org/wiki/Separation_of_concerns
Update:
E.g. Instead of having your reel resizing code inline, put it in it's own function, like this:
function setImageReelWidth () {
//Get size of images, how many there are, then determin the size of the image reel.
var divWidth = $(".window").width();
var divSum = $(".slide").size();
var divReelWidth = divWidth * divSum;
//Adjust the image reel to its new size
$(".image_reel").css({ 'width': divReelWidth });
}
This achieves 2 things:
a. First, it groups a block of code that is logically cohesive, removing it from the main code which results in a much cleaner code habitat.
b. It effectively gives a label to the code block via the function name that is descriptive of what it does, and therefore makes understanding of the code much simpler.
Later, you can also encapsulate the whole thing in it's own "class" (function) and you can move it into it's own js file.
2) The jQuery "on" function
Use the "on" function to attach your click events, rather than the "click" function.
http://api.jquery.com/on/
This has the added advantage of also binding it to future elements matching your selector, even though they do not exist yet.
3) The ready function
// I like the more succinct:
$(handler)
// Instead of:
$(document).ready(handler)
But you might like the more obvious syntax.
Those are just a few things to start with.
-- Update 1 --
Ok, StackOverflow is not really suited to a refactoring work in progress, but we'll make do. I think you should keep your original code block in your question, so that future readers can see where it started and how it systematically improved.
I would like to know more about the create a new function, outside of
the jQuery ready block as i cant get this working or quite understand
how i can get it to work sorry
I am not familiar with jsfiddle.net, but it looks cool and helpful, but might also be a bit confusing if you don't know what is going on. I am not sure I do :), but I think that script editor window results in a .js file that is automatically referenced by the html file.
So here is an example of a function defined outside of the ready block, but referenced from within.
function testFunction () {
alert ('it works');
}
$(document).ready(function () {
testFunction();
// ... other code
});
This should pop up an alert box that says, "it works" when the page is loaded.
You can try it for yourself.
Then, once you got that working, you can refactor other logically cohesive blocks of code into their own functions. Later you can wrap them all up into their own javascript 'class'. But we'll get to that.

Categories