Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Jquery Slider Div Re: Jquery Slider Div

#127741
Mottie
Member

Hi rczilok!

Try [this demo](http://jsfiddle.net/Mottie/cPLct/4/)

There are a few things to note:

* Wrap all of the content so we can use css position to move content around. If you need help understanding how css positioning works, [this tutorial](http://www.barelyfitz.com/screencast/html-training/css/positioning/) is very helpful!
* Add a class name to each content block to make targeting them easier – I used `content` in this case.
* Changing the width doesn’t always work, so change the left position of the content to animate it around.
* A variable named `contentWidth` is set to contain the negative left position of the content to keep it hidden off screen to the left. It grabs the width of the first content block, not the widest.
* The animate function that moves the content off the screen to the right is actually calculating the width of the browser window and moving the content past it. Then when the animation completes, it resets the left position to hide the content.

Hopefully I added enough comments in the code so it is clear what each section is doing.

Here is the full code for prosperity (in case jsFiddle breaks)

HTML

CSS

.wrapper {
position: relative;
}
.content {
width: 300px;
height: 300px;
padding: 0;
left: 0;
top: 0;
}
.box {
width: 300px;
height: 300px;
}
#one .box {
background: red;
}
#two .box {
background: blue;
}
#three .box {
background: green;
}
ul li {
display: inline;
padding-right: 10px;
list-style: none;
}

Script

$(function () {

// get the width of the first content box
// add a bit of extra so we end up with “-350px”
var contentWidth = ‘-‘ + ($(‘.content’).width() + 50) + ‘px’;

// reposition the content here in case javascript is disabled
$(‘.content’).css({
position: ‘absolute’,
left: contentWidth
});

$(“li a”).click(function () {
event.preventDefault();
var $blockID = $( $(this).attr(‘href’) );
// if the content is already showing, don’t do anything
if ($blockID.hasClass(‘visible’)) { return; }
// hide any visible content
$(‘.content.visible’)
.removeClass(‘visible’)
// move the old content past the current window width, then reset it’s position
.animate({
left: $(window).width()
}, function () {
// Remove left setting after the animation completes
$(this).css(‘left’, contentWidth);
});
$blockID
.addClass(‘visible’)
.animate({ left: 0 });
});

});