Javascript/Jquery - Don't repeat yourself - javascript

I've seen this so many times on the internet. People say to don't repeat yourself in programming languages. I wrote this script for my webpage but I repeated myself quite a bit.
Is it really that big of a deal?
Should I make a function?
How do I do it?
var active = '.teachers';
var disabled = '.teacher-link';
var width = $('.teachers .staff-outer-container').children().size() * 180;
$('.staff-outer-container').css('width', width + 'px');
$('.teacher-link').click(function() {
if (active != '.teachers') {
$(active).hide();
active = '.teachers';
$(active).show();
width = $('.teachers .staff-outer-container').children().size() * 180;
$('.teachers .staff-outer-container').css('width', width + 'px');
$(disabled).removeClass('active').addClass('clickable');
disabled = this;
$(disabled).removeClass('clickable').addClass('active');
$('#type').text('Teachers');
}
});
$('.admin-link').click(function() {
if (active != '.administrators') {
$(active).hide();
active = '.administrators';
$(active).show();
width = $('.administrators .staff-outer-container').children().size() * 180;
$('.administrators .staff-outer-container').css('width', width + 'px');
$(disabled).removeClass('active').addClass('clickable');
disabled = this;
$(disabled).removeClass('clickable').addClass('active');
$('#type').text('Administrators');
}
});
$('.support-link').click(function() {
if (active != '.support') {
$(active).hide();
active = '.support';
$(active).show();
width = $('.support .staff-outer-container').children().size() * 180;
$('.support .staff-outer-container').css('width', width + 'px');
$(disabled).removeClass('active').addClass('clickable');
disabled = this;
$(disabled).removeClass('clickable').addClass('active');
$('#type').text('Support Staff');
}
});
edit
Thanks for everyone's input! I'm confused on how to implement these functions. This is what I got: $('.teacher-link').click(handle_click('.teachers', 'Teachers')); I tried this out and it didn't work.
Also where do I place the function? Do I place it inside or outside $(document).ready ? Is it best to put functions at the start or the end of my script?

You could build a function like this, and call it like:
handle_click('.teachers', 'Teachers');
handle_click('.adminstrators', 'Administrators');
etc.
Function:
function handle_click(target, target_text) {
if (active != target) {
$(active).hide();
active = target;
$(active).show();
width = $(target + ' .staff-outer-container').children().size() * 180;
$(target + ' .staff-outer-container').css('width', width + 'px');
$(disabled).removeClass('active').addClass('clickable');
disabled = this;
$(disabled).removeClass('clickable').addClass('active');
$('#type').text(target_text);
}
}

"Is it such a big deal"?
It is NOT a big deal as long as everything works ok.
It is a big deal if something breaks down or you have to change/add some features.
It is NOT a big deal if it's a small piece of code which you handle all by yourself
It is a big deal if someone else needs to work with your code and it will be extended in the future.
Personaly I think that if you are hours after deadline and stuff needs to be published ASAP, you can keep messy and redundant code - but only if it is refactored afterwards. The problem is that, probably, once the code is published no one will look and refactor it, unless it get's broken or generates bugs.
Look at your code - what if someone decides that a new feature would be generating dynamic objects and handling them with those functions, using loops and stuff?
With your code this is impossible and after all you'll need to make it automatic. So why not make it correct in the first place? I think that making the code automatic will cost muuuuuch less time than fixing it if something bad happens.

function switchActive(tag,name)
{
if (active != tag) {
$(active).hide();
active = tag;
$(active).show();
width = $(tag+' .staff-outer-container').children().size() * 180;
$(tag+' .staff-outer-container').css('width', width + 'px');
$(disabled).removeClass('active').addClass('clickable');
disabled = this;
$(disabled).removeClass('clickable').addClass('active');
$('#type').text(name);
}
}
$('.teacher-link').click(function(){switchActive('.teacher','Teachers');});
$('.admin-link').click(function(){switchActive('.administrators','Administrators');});
$('.suppport-link').click(function(){switchActive('.support','Support Staff');});

That's one of the basics of sotware engineering. If a task has to be made twice, it has to be automatized. There you got a pattern that can be put in a function, or a class method, depending on the context of usage. I can give you an example of such a function, but that wouldn't be a good example, without having a thorough thought of that in the execution context.
function link_click(linkClass, targetClass, text) {
$(linkClass).click(function() {
if (active != targetClass) {
$(active).hide();
active = targetClass;
$(active).show();
width = $(linkClass + ' .staff-outer-container').children().size() * 180;
$(linkClass + ' .staff-outer-container').css('width', width + 'px');
$(disabled).removeClass('active').addClass('clickable');
disabled = this;
$(disabled).removeClass('clickable').addClass('active');
$('#type').text(text);
}
});
There are so many different ways to do it (as you can see in the different answers over here), and I'm pretty sure none of them is totally a fit for your usage. You may prefer to make a class that has one or more methods for that purpose, so you can make different ways to execute your function, or create a new event or something else I don't think of now...
Take a break, look overall at your code, what you would need for potential future improvements so the stuff you write today don't get in the way tomorrow.

You are doing well. However you can improve that your code be more productivity and reusability. It is not good solution but it will help you for some idea.
<script>
$(function(){
$('.tab-link').click(function() {
if($(this).hasClass("active") == false) {
var target = $( $(this).attr("href") );
$(".tab-section").hide();
target.show();
$(".tab-link").removeClass("active").addClass("clickable");
$(this).removeClass("clickable").addClass("active");
var container = target.find("staff-outer-container");
var width = container.children().size() * 180;
container.css("width", width + "px");
$("#type").text($(this).html());
}
});
});
</script>
<a class="tab-link" href="#staff-teacher">Teachers</a>
<a class="tab-link" href="#staff-admin">Administrators</a>
<a class="tab-link" href="#staff-support">Support Staff</a>
<h1 id="type">Teachers</h1>
<div id="staff-teacher" class="tab-section">
<div class="staff-outer-container">
#Teacher List
</div>
</div>
<div id="staff-admin" class="tab-section">
<div class="staff-outer-container">
#Admin List
</div>
</div>
<div id="staff-support" class="tab-section">
<div class="staff-outer-container">
#Staff List
</div>
</div>

You could write something like this, fully extensible:
(only defined active,disabled variables so this actually works in jsfiddle)
jsfiddle: http://jsfiddle.net/8RaXv/2/
var active=document.getElementById('active'),
disabled=document.getElementById('disabled'),
teacher = {
$link: $('.teacher-link'),
selector: '.teachers',
text: 'Teachers'
},admin = {
$link: $('.admin-link'),
selector: '.administrators',
text: 'Administrators'
},support = {
$link: $('.support-link'),
selector: '.support',
text: 'Support Staff'
};
bindHandler([teacher, admin, support]);
//bind handlers
function bindHandler(items) {
for (var i in items) {
items[i].$link.on('click', items[i], clickHandler);
}
}
//generic handler
function clickHandler(event) {
var context = event.data;
if (active !== context.selector) {
$(active).hide();
active = context.selector;
$(active).show();
var $container = $(context.selector + ' .staff-outer-container');
width = $container.children().size() * 180;
$container.css('width', width + 'px');
$(disabled).removeClass('active').addClass('clickable');
disabled = this;
$(disabled).removeClass('clickable').addClass('active');
$('#type').text(context.text);
}
}

Related

Drag and drop anywhere on screen with multiple elements of the same ID Class and Tag HTML

Hello everyone this is my first question so I might have done it wrong.
What I am trying to achieve is is have multiple <aside> elements all with the same ID Class and of course Tag be able to be moved anywhere on the screen with drag and drop characteristics. I have found a JSFiddle demonstrating the code I am basing this around that uses one aside element with the ability to be moved anywhere, but will not work when multiple elements are used. The code controlling the movement is here:
function drag_start(event) {
var style = window.getComputedStyle(event.target, null);
event.dataTransfer.setData("text/plain",
(parseInt(style.getPropertyValue("left"),10) - event.clientX) + ',' +
(parseInt(style.getPropertyValue("top"),10) - event.clientY));
}
function drag_over(event) {
event.preventDefault();
return false;
}
function drop(event) {
var offset = event.dataTransfer.getData("text/plain").split(',');
var dm = document.getElementById('dragme');
dm.style.left = (event.clientX + parseInt(offset[0],10)) + 'px';
dm.style.top = (event.clientY + parseInt(offset[1],10)) + 'px';
event.preventDefault();
return false;
}
var dm = document.getElementById('dragme');
dm.addEventListener('dragstart',drag_start,false);
document.body.addEventListener('dragover',drag_over,false);
document.body.addEventListener('drop',drop,false);
The part I am having trouble with is the drop system which requires the elements to have individual ids. I also need to have all aside elements have to same id and I don't want to use classes. I have tried and thought and searched the web for the past three days with no luck of finding an answer as all link back to this same code. I have looked into getting the index of the last element clicked but cannot find a way to get all elements with the same ID. Thanks in advanced - bybb
Update: Have broken the dnd system need help with that:
var dragindex = 0;
$(document).ready(function(){
$("aside").click(function(){
dragindex = $(this).index();
});
});
function drag_start(event) {
var style = window.getComputedStyle(event.target, null);
event.dataTransfer.setData("text/plain",
(parseInt(style.getPropertyValue("left"),10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"),10) - event.clientY));
}
function drag_over(event) {
event.preventDefault();
return false;
}
function drop(event) {
var offset = event.dataTransfer.getData("text/plain").split(',');
var dm = document.getElementById('#winborder');
dm.style.left = (event.clientX + parseInt(offset[0],10)) + 'px';
dm.style.top = (event.clientY + parseInt(offset[1],10)) + 'px';
event.preventDefault();
return false;
}
function makewindow(content, storevar) {
storevar = document.createElement('aside');
storevar.setAttribute("dragable", "true");
storevar.setAttribute("id", "winborder");
var content = document.createElement('div');
content.setAttribute("id", "wincontent");
storevar.appendChild(content);
document.body.appendChild(storevar);
storevar.addEventListener('dragstart',drag_start,false);
document.body.addEventListener('dragover',drag_over,false);
document.body.addEventListener('drop',drop,false);
}
Have tried with and without '#' on getelementbyid
The following code will allow drag and drop; I'm sorry it doesn't follow your previous coding style.
Here is a JSFiddle showing it in action: https://jsfiddle.net/6gq7u8Lc/
document.getElementById("dragme").onmousedown = function(e) {
this.prevX = e.clientX;
this.prevY = e.clientY;
this.mouseDown = true;
}
document.getElementById("dragme").onmousemove = function(e) {
if(this.mouseDown) {
this.style.left = (Number(this.style.left.substring(0, this.style.left.length-2)) + (e.clientX - this.prevX)) + "px";
this.style.top = (Number(this.style.top.substring(0, this.style.top.length-2)) + (e.clientY - this.prevY)) + "px";
}
this.prevX = e.clientX;
this.prevY = e.clientY;
}
document.getElementById("dragme").onmouseup = function() {
this.mouseDown = false;
}
On a side note, you won't be able to give them all the same id. The DOM doesn't support such a thing. If you want to add multiple elements of the same type, I would suggest a 'container' parent div, adding the elements as children of the div, and iterating through the .children attribute to access each.
Don't know if you want to use Jquery or not, but I know it's way simpler than the raw javascript solution. I've been searching the internet and Stack Overflow for a simple drag-and-drop anywhere on a web page solution, but I couldn't find one that worked. The other answers to this question have been weird for me. They sometimes work, sometimes don't. However, a friend suggested using the Jquery version, and wow, it's so much simpler. Just one line of code!
var dragme = document.getElementsByClassName("dragme");
for (var i = 0; i < dragme.length; i++) {
$(dragme[i]).draggable();
}
.dragme {
cursor: move;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<h1 class="dragme">Try dragging me anywhere on this sample!</h1>
<h2 class="dragme">Drag me, too!</h2>
IMPORTANT NOTE: This code does not work with just Jquery, it also requires the Jquery UI file.
If the above sample does not work for you, please comment the error it show below. Note that this works for an unlimited amount of elements. This specific example is for elements with the class "dragme", so just replace that with your own class. For one element, it is a single line of code: $("#yourid").draggable();.
This code works for me on Google Chrome. Hope this helps anyone coming on to this page late, like me!

How can I have two of these on one page with different variables? (JQuery)

I need to have 2 of these one page but each with different percentages. When I try re-writing the JS or even use different class/ID names it still always pulls from the first SPAN.
http://jsfiddle.net/K62Ra/
<div class="container">
<div class="bw"></div>
<div class="show"></div>
<div id="bar" data-total="100">
<div class="text">Currently at <br/><span>70</span><br><i>Click To Give</div>
</div>
JS and CSS in the Fiddle.
Much Thanks.
This one will work smoothly:
http://jsfiddle.net/K62Ra/7/
$('.bar').each(function() {
var percentStart = 0;
var total = $(this).data('total');
var percent = parseInt($(this).find('span').html());
$(this).find('> div').addClass("load");
var that = this;
var timer = setInterval(function() {
$(that).siblings('.show').css('height', percentStart/total*100+'%');
$(that).css('height', percentStart/total*100+'%');
$(that).find('span').html('%'+percentStart);
if(percentStart<percent) { percentStart=percentStart+1; return; }
clearInterval(timer);
}, 35);
});
The interval has to be terminated as well, or it will run infinitely (though not doing anything).
I've changed your id="bar" into a class. Then I'm running a each loop for the .bar classes. here is the fiddle: http://jsfiddle.net/K62Ra/3/
here is the code:
$('.bar').each(function (index, element) {
percent = $(this).find('span').html();
total = $(this).attr('data-total');
percentStart = 0;
setInterval(function () {
$('.show').css('height', percentStart / total * 100 + '%');
$(this).css('height', percentStart / total * 100 + '%');
$(this).find('span').html('%' + percentStart);
if (percentStart < percent) {
percentStart = percentStart + 1;
}
}, 35);
});
$(".bar div").addClass("load");
Like some of the comments have stated, having duplicate ids is bad design and can cause some weird errors.
You can find a solution to your problem by changing a number of things. One, instead of
referring to divs in you selectors by id'#', you can infer them by class '.' like
$('.bar')
The next step would be to ensure exclusivity for each div with class 'container' by using a closure
$('.container').each(function(){
var x
var y
.
.
});
And finally, avoid 'selecting' elements in the selector directly, but use $(this) and .find() to ensure you are within the current div with class 'container'.
http://jsfiddle.net/K62Ra/5/
$('.container').each(function(){
var percent = $(this).find('div.bar div span').html();
var total = $(this).find('div.bar').attr('data-total');
var percentStart = 0;
var that = $(this);
setInterval(function() {
that.find('.show').css('height',percentStart/total*100+'%');
that.find('div.bar').css('height',percentStart/total*100+'%');
that.find('div.bar div span').html('%'+percentStart);
if(percentStart<percent) {percentStart=percentStart+1;}
},35);
$(this).find("div.bar div").addClass("load");
});
There are already several good answers here. I would recommend validating your html. Also some of your css was causing weirdness when there was scrolling involved (fixed background images weren't scrolling.)
I took a slightly different approach than everyone else. Instead of using a setInterval I went with $.animate and a step function. Like others, I chose a class to target each of the items: 'fill-me-up'.
Fiddle: http://jsfiddle.net/LFbKs/6/
NOTE: Check the fiddle since I modified the HTML (very slightly) and the css to a larger degree.
// for each item we need to "fill up"
$('.fill-me-up').each(function(){
// cache DOM references
var this$ = $(this)
, bar$ = this$.find('.bar')
, show$ = this$.find('.show')
, span$ = bar$.find('div span')
// the target percentage height for this item
, p = span$.text()
// combine '.bar' and '.show' so we can apply the animation to both
, toAnimate = $().add(bar$).add(show$);
// add class causing fade-in
bar$.find('div').addClass('is-visible');
// animate height to target height over 2 seconds and
// at each step, update the span with a truncated value
toAnimate.animate(
{ height: p+'%' },
{
duration: 2000,
step: function( currentStep ) {
span$.html('%'+currentStep.toFixed(0));
}
}
);
});
Cheers

box-sizing x IE7, the last battle

I've been searching through the web for a solution that can viabilize box-sizing in the IE7 (I know, the year is 2014, but the project (therefore the clients) still demand this). I really need box-sizing because the entire project is responsive.
I found this boxsizing.htc and it works pretty well in almost any case. But, unfortunately, it is not my case.
Because I'm using angularjs and I have a div with three columns (children divs with float left) inside and i can click on a button to change the number of columns. When this happens the boxsizing.htc process all its calculations again making my width and height smaller each time I change the number of columns.
So, I thought, angularjs can solve this. I found this pretty interesting link
I could adapt that code into this:
myApp.directive('resizable', function($window){
return {
restrict: 'A',
link: function(scope, element){
scope.initializeWindowSize = function(){
var win = angular.element($window);
scope.windowHeight = win.innerHeight();
scope.windowWidth = win.innerWidth();
scope.sideHeight = scope.windowHeight - 80;
/* ie 7 */
var workArea = angular.element('.workArea');
var workWidthPadding = parseInt(workArea.css('paddingLeft')) + parseInt(workArea.css('paddingRight')) + parseInt(workArea.css('borderRightWidth')) + parseInt(workArea.css('borderLeftWidth'));
var workHeightPadding = parseInt(workArea.css('paddingTop')) + parseInt(workArea.css('paddingBottom')) + parseInt(workArea.css('borderTopWidth')) + parseInt(workArea.css('borderBottomWidth'));
scope.workWidth = scope.windowWidth - 228 - 210 - workWidthPadding;
scope.workHeight = scope.sideHeight - 60 - 25 - 2 - workHeightPadding;
console.log('height', scope.workHeight);
};
scope.initializeWindowSize();
angular.element($window).bind('resize',function(){
scope.initializeWindowSize();
scope.$apply();
});
}
}
});
But that code don't solve all of my problems, just when I can relate the div's width or height with window width or height which it is not all the cases.
Finally, I decide, let's make a jQuery plugin. I came up with this:
$.fn.boxsizing = function(){
// if(navigator.appVersion.indexOf("MSIE 7.") != -1){
var thisWidth = this.width(),
thisHeight = this.height(),
thisborderLeft = parseInt(this.css('borderLeftWidth')),
thisborderTop = parseInt(this.css('borderTopWidth')),
thisborderRight = parseInt(this.css('borderRightWidth')),
thisborderBottom = parseInt(this.css('borderBottomWidth')),
thispaddingLeft = parseInt(this.css('paddingLeft')),
thispaddingTop = parseInt(this.css('paddingTop')),
thispaddingRight = parseInt(this.css('paddingRight')),
thispaddingBottom = parseInt(this.css('paddingBottom')),
newWidth = thisWidth - thisborderLeft - thisborderRight - thispaddingLeft - thispaddingRight,
newHeight = thisHeight - thisborderTop - thisborderBottom - thispaddingTop - thispaddingBottom;
console.log(newWidth, newHeight);
this.css({'width':newWidth, 'height':newHeight});
// }
}
This almost worked.
I can't figured how to apply this code in window resize.
$(window).resize(function(){
$('div.FOO').boxresizing();
});
Can someone help? I don't know if angularjs can handle alone this kind of stuff or, if I really need this plugin and, how can I make things work in the window resize.
Thank you and sorry for my poor english.

Prevent lagging in DOM

So I am writing a sort of drawing script, and it works fine right now (although the code still needs to be cleaned up and there needs to be more features), but when painting too much, mousemove lags incredibly. Here is the main Javascript:
$('#canvas').on('mousedown', function(){
going = !going;
$(this).on('mousemove', function(e){
if(cursor == 'paint' && going == true){
$('.fall').each(function(){
if ($(this).css("opacity") == 0){
$(this).remove();
};
});
var ps = $('#canvas').offset().top;
var t = (e.pageY - ps - $('.fall').height()).toString() + 'px';
var l = (e.pageX - $('.fall').width()).toString() + 'px';
$('.fall').css("margin_left",l);
$('.fall').css("margin_top",t);
var doit = '<div class="fall" style="position:absolute;margin-left:' + l + ';margin-top:' + t + ';background-color:'+ color +';box-shadow: 0px 0px 5px ' + color + ';"></div>'
$('#canvas').prepend(doit);
}
else if(cursor == 'erase'){
$('.fall').mouseenter(function(){
$(this).fadeOut('fast',function(){
$(this).remove()
});
});
};
});
Essentially, when you click in the section for drawing, if the paint button is clicked, you can draw: jsfiddle.
My issue:
If you draw too much, especially with starting and stopping, it does not append enough on the mousemove do to (I assume) the DOM being overwhelmed.
Question:
What would be an efficient way to add many many divs to the DOM without creating a lag? Is this possible?
Note:
this is a personal project and I am not interested in using previously created drawing APIs
There's a lot you can do to improve performance.
The code below is a heavy refactoring of the code in the question. At first glance it might appear to be less efficient as it has about double the number of lines of the original. However, line count isn't the issue here. Two basic principles apply:
do as little DOM interaction as possible in the mousemove handler, and as much as possible on mousedown.
include a "divider circuit" to limit the number of times the mousemove handler is called. This is achieved by detaching the mousemove event handler on every call and reattaching after a short delay, conditional on the mouse still being down.
Also see comments in the code.
jQuery(function($) {
...
var $canvas = $("#canvas");
var data = {
name: 'fall'//a unique string for namespacing the muousemove event.
};
$canvas.on('mousedown', function() {
going = !going;
data.$fall = $('.fall');//this collection is created once per mousedown then managed inside mm to avoid unnecessary DOM interaction
data.mousedown = true;
data.colorCSS = {
'background-color': color,
'box-shadow': '0px 0px 5px ' + color
};
data.fallWidth = data.$fall.width();
data.fallHeight = data.$fall.height();
attachMouseMoveHandler();
}).on('mouseup', function() {
data.mousedown = false;
}).trigger('mouseup');
function attachMouseMoveHandler() {
if(data.mousedown);
$canvas.on('mousemove.' + data.name, mm);//the event is namespaced so its handler can be removed without affecting other canvas functionality
}
//The mousemove handler
function mm(e) {
if(going && cursor == 'paint') {
data.$fall.each(function() {
data.$fall = data.$fall.not(this);//manage data.$fall rather than re-form at every call of mm()
var $this = $(this);
if ($this.css("opacity") == 0) {
$this.remove();
};
});
data.$fall = data.$fall.add($('<div class="fall" />').css(data.colorCSS).prependTo($canvas)).css({
'margin-left': (e.pageX - data.fallWidth) + 'px',
'margin-top': (e.pageY - $canvas.offset().top - data.fallHeight) + 'px'
});
}
else if(cursor == 'erase') {
data.$fall.mouseenter(function() {
data.$fall = data.$fall.not(this);//manage data.$fall rather than re-form at every call of mm()
var $this = $(this).fadeOut('fast', function() {
$this.remove();
});
});
};
$canvas.off('mousemove.' + data.name);
setTimeout(attachMouseMoveHandler, 50);//adjust delay up/down to optimise performance
}
});
Tested only for syntax
I had to make a number of assumptions, chiefly concerning what becomes fixed data on mousedown. These assumptions may be incorrect, so you will most probably still have some work to do, but as long as you work inside the overall framework above, there's a good chance that your performance issues will disappear.

JavaScript or jQuery image carousel/filmstrim

I am looking for some native JavaScript, or jQuery plugin, that meets the following specification.
Sequentially moves over a set of images (ul/li)
Continuous movement, not paging
Appears infinite, seamlessly restarts at beginning
Ability to pause on hover
Requires no or minimal additional plugins
I realize this sounds simple enough. But I have looked over the web and tried Cycle and jCarousel/Lite with no luck. I feel like one should exist and wanted to pose the question before writing my own.
Any direction is appreciated. Thanks.
you should check out Nivo Slider, I think with the right configuration you can it to do what you want.
You can do that with the jQuery roundabout plugin.
http://fredhq.com/projects/roundabout/
It might require another plugin.
Both answers by MoDFoX and GSto are good. Usually I would use one of these, but these plugins didn't meet the all the requirements. In the end this was pretty basic, so I just wrote my own. I have included the JavaScript below. Essentially it clones an element on the page, presumably a ul and appends it to the parent container. This in effect allows for continuous scrolling, right to left, by moving the element left and then appending it once out of view. Of course you may need to tweak this code depending on your CSS.
// global to store interval reference
var slider_interval = null;
var slider_width = 0;
var overflow = 0;
prepare_slider = function() {
var container = $('.sliderGallery');
if (container.length == 0) {
// no gallery
return false;
}
// add hover event to pause slider
container.hover(function() {clearInterval(slider_interval);}, function() {slider_interval = setInterval("slideleft()", 30);});
// set container styles since we are absolutely positioning elements
var ul = container.children('ul');
container.css('height', ul.outerHeight(true) + 'px');
container.css('overflow', 'hidden')
// set width and overflow of slider
slider_width = ul.width();
overflow = -1 * (slider_width + 10);
// set first slider attributes
ul.attr('id', 'slider1');
ul.css({"position": "absolute", "left": 0, "top": 0});
// clone second slider
var ul_copy = ul.clone();
// set second slider attributes
ul.attr('id', 'slider2');
ul_copy.css("left", slider_width + "px");
container.append(ul_copy);
// start time interval
slider_interval = setInterval("slideleft()", 30);
}
function slideleft() {
var copyspeed = 1;
var slider1 = $('#slider1');
var slider2 = $('#slider2');
slider1_position = parseInt(slider1.css('left'));
slider2_position = parseInt(slider2.css('left'));
// cross fade the sliders
if (slider1_position > overflow) {
slider1.css("left", (slider1_position - copyspeed) + "px");
}
else {
slider1.css("left", (slider2_position + slider_width) + "px");
}
if (slider2_position > overflow) {
slider2.css("left", (slider2_position - copyspeed) + "px");
}
else {
slider2.css("left", (slider1_position + slider_width) + "px");
}
}

Categories