In this tutorial I’m going to teach you how to construct a simple UI slider using jQuery. It’s very effective and can be used for almost anything. You can slide through text, pictures, videos, etc. So let’s get started!
You’ll first need to set up the HTML and add some basic styling to the content. So within the body of the HTML file, we’ll write:
This sets up a “main_body” div that contains everything within in. Then it has the “content-slider” div which will be the actual sliding bar. The “content-scroll” div is what will be controlled by the sliding funtcions we write later in jQuery. And finally the “content-holder” div is simply what contains the plain text that is written; all the paragraphs also have the same class attributed to them.
Here’s the CSS setup with comments so you can understand what each property does:
So as you can see, we set up a pretty simple base for our content slider. When you open up the HTML file, the content should look like this.
The reason you only see one of the paragraphs now is because we aligned each paragraph to be floated to the left, and we set each of them to have their own width, so that means all the other paragraphs are all aligned right next to each other, you just can’t get to them yet.
Since everything seems to be properly aligned, let’s add an actual slider function so that we can slide through all our content.
The first function, “function slide_change(e, ui)” focuses on the actual changing from one content area to another. The function takes the arguments event & ui, which is why the e and ui are in parentheses. It sets the variable maxScroll to equal a certain width by subtracting one width from the other. Then the animate function will allow an animaton to take place when you slide the slider from one point to another. The speed is set to 800 milliseconds. You can change this number to get some different effects.
The second function, “function slider_sliding(e, ui)” focuses on the slider knob you move. This event is triggered by every mouse move during the slide. It syncs up the slider with the content.
Then we set te final properties. We access “#content-slider” and set it to be our slider. Then we set animations to be true, and its change option is the function “slide_change” and our slider option comes from the “slider_sliding” function. After the jQuery commands, there’s one more thing left to do, and that’s set up the CSS for the sliding knob.
To access the slider in the CSS, use the class “.ui-slider-handle”. So for this example write up the CSS like so:
And that’s it you’re done! You can play around a little with the functions and CSS styling to make it look and work exactly how you want it to. Thanks for reading the tutorial and hopefully learning something new!
You can check out an example here!