10
X

How to Create a Simple Image Slider Using jQuery

Image sliders are useful for showing multiple images with cool animations to catch a user’s attention.  Having an image slider/slideshow is a very common functionality that you may find on any website. Creating a simple image slider is pretty easy and it can be implemented easily with jQuery. There are tons of plugins available for creating image sliders using jQuery plugins, but one should be careful while using jQuery plugins as jQuery plugins consumes bandwidth and may increase page load time. If things can be done with jQuery code, one should not use any plugin. In this post, let’s see how to create simple image slider using jQuery.

HTML Markup

 

First, let’s take a look at HTML markup.  There is a parent div element and a child div element which contains all the image tags. Here, the child div element tag will be used for rotation of the images in the jQuery code.

<div id="sliderContainer">
<div id="sliderWrapper">
<img src="img/1.jpg" />
<img src="img/2.jpg" />
<img src="img/3.jpg" />
<img src="img/4.jpg" />
<img src="img/5.jpg" />
</div>
</div>

CSS

Below CSS code, used for parent slide container and for the individual images. This code will set the width of slider container to 800 pixels. It’s important to note that overflow: hidden property is applied to hide other images except the current one, otherwise all images would be visible on the screen. One thing to also note here that if your images are greater than 800px then you may need to adjust the width property accordingly.

#sliderContainer {
  width: 800px;
  margin: 0;
  padding: 0px;
  position: relative;
  overflow: hidden;
}
#sliderContainer .slider {
  margin: 0;
  padding: 0;
  width: 800px;
  float: left;
  position: relative;
}

 

jQuery Code

First, define few variables.

  • The first variable curPos, indicates the current position and it is set to 0.
  • Second variable is slider which gets the references of all images with CSS class “.slider”.
  • Third variable is cntImages, which gets the count of total number of images which are part of slider.
  • And the fourth variable is sliderWidth, which gets the width of slider container.

There were 2 div element defined in the HTML markup sliderContainer and sliderWrapper. The logic of creating image slider is, assign the total width to sliderWrapper which is sliderWidth * cntImages. So in this case, this value comes to 4000px (800×5). But it won’t be visible on the screen as parent element is having overflow:hidden property.

Next, create a function called SlideImage, which will be called by setInterval function with delay of 2 seconds. This ensures that images rotates automatically. Inside this function,

  • First checks, if the current image is the last image. If yes, then set curPos variable to 0 so that first image is shown again. And if not, then we increment the value of curPos variable.
  • To show next image as part of image slider, we play with the margin-left property of sliderWrapper so that next image becomes part of slider visible area. We use animate method of jQuery which provides us the slide animation. And we set margin-left property to sliderWidth * (-curPos). So the value for image 2 would be -800, -1600 for third image, -2400 for fourth image and -3200 for last image. And again back to 0 for first image. And that would make images to rotate.

Here is complete jQuery code.

$(function() {
  var curPos = 0;
  var slider = $('.slider');
  var cntImages= slider.length;
  var sliderWidth = slider.width();
  $('#sliderWrapper').css('width', sliderWidth * cntImages);
  setInterval(SlideImage, 2000);

  function SlideImage() {
    if (curPos == cntImages - 1)
      curPos = 0;
    else
      curPos++;
     $('#sliderWrapper').animate({
      'marginLeft': sliderWidth * (-curPos)
    });
  }
});

What next?

This is a simple jQuery image slideshow with 5 images and you can add more images. All you need to do is to just add image tag. You can also modify the jQuery code as per your requirement and control the speed of image rotation via setting a higher delay for setInterval method.

Caching Elements in jQuery

If you cache your jQuery elements, it means that you store an element as a variable so that you can re-use that element without your jQuery having to re-query the DOM in search of it every time you want to apply some code to that element. It’s not always necessary, but in cases where you know you’ll be using certain elements a lot in your code, it’s not a bad idea to cache them, because that’ll help your code work faster and more efficiently.

Here’s how you would cache an element, it’s actually super simple! For this example, let’s cache a class called .main:

 var main = $(“.main”);

That’s literally all it takes to cache an element. Then when you want to use it later, you just have to refer back to the name that you gave you variable, like this:

 main.css(“color”, “blue”);

The code above will change the CSS so that the color of the text in the .main class is blue. You can cache as many selectors as you like and give the variables whatever name you like, and this should help keep your code light and clean.

Show/Hide HTML Elements Using jQuery

jQuery’s .show() and .hide() methods can be used to show or hide any HTML elements on a page. Usually, the methods are used as the results of a trigger event (for example, if an item is either hidden or shown based on a click event) or used with a timer function so that something hides or shows based on how long a page has been loaded for. Whatever context you choose to use .show() or .hide() methods, they’re pretty handy and easy to understand.

For an example of how you would use the methods as a result of a click event, see the code below:

$(“.button”).click(function(){
    $(“h1”).show();
})

The example above demonstrates how you would use a click event to trigger an element appearing on a page. After the .button class is clicked, any h1 on the page that is hidden would be shown. Using the .hide() method instead would require the exact same syntax.

The .show() and .hide() methods also take a speed parameter that allows you to define the speed at which you’d like to have the selected elements appear or disappear. You can define the speed as a number (in milliseconds) or string (slow, fast). See an example of how to use the speed parameter below:

$(“.button”).click(function(){
$(“h1”).hide(400);
})

There are also a few other parameters that the .show and .hide methods will accept, including easing effects. As with most jQuery methods, you can also place a callback function within the method’s parentheses to be executed after the show/hide event.

jQuery’s .fade() Method

In jQuery, there several different methods that can be used to make an element fade in and out of view. They are: .fadeIn(), .fadeoOut(), .fadeToggle(), and .fadeTo().

.fadeIn() and .fadeOut() are pretty self explanatory. When triggered, it is used to have items either fade in or fade out, respectively. .fadeToggle() is used to toggle between .fadeIn() and .fadeOut(), so when .fadeToggle() is triggered the first time, the elements will fade out, and when it’s triggered again, they’ll fade in. If it’s triggered a third time, the elements will fade back out. .fadeTo() is used to partially fade elements out. With .fadeTo() you can control the opacity level that the elements fade to.

Here’s an example of how you would use .fadeOut() in context:

$(“.main”).click(function(){
$(this).fadeOut(“slow”);
})

When the code in the above example is executed, the .main element will fade out at a slow rate when it’s clicked. The two parameters that the .fadeOut() method takes are speed (could be in milliseconds or in fixed values like slow), and a callback, which gives you the option to insert another function to be executed once the fade is complete. .fadeIn() and .fadeToggle() take the same parameters.

How to Use jQuery’s .one() Method

jQuery’s .one() method is a really cool method that, when used, will trigger a function attached to a certain selector or element only once. Normally with jQuery methods, they will occur as many times as the trigger event is triggered, but when you use the .one() method, the code that it’s attached to only gets executed once per page load.

As an example, let’s say we wanted to use the .one() method to trigger an alert when a button with the class “.alert-button” is clicked, and we only want this to happen ONE time (so if the user clicks the button twice or three times, the alert will only have shown up after the first click. This is actually pretty easy to employ in your jQuery. To see how it works, check out the code below.

$(".alert-button").one("click", function(){
 alert("This alert message will only appear once!");
 })

So once that .alert-button button is clicked, the alert will pop up. But if the button is clicked again, no alert message will appear. We’ve found this method to be extremely useful because often in our projects we do want to limit actions to occurring only once, and it’s great to have a simple and effective way to do that.

Using jQuery to Check All Boxes

If you want to include a “check all” option in any of your projects, it’s actually pretty easy to do using jQuery. The snippet below demonstrates how to include a check all button that will check all of the inputs that fall within one fieldset tag. To start, make sure your HTML looks something like this:

<fieldset>
<input type="checkbox" class="checkall"> Check all <br>
<input type="checkbox"> Checkbox <br>
<input type="checkbox"> Checkbox <br>
<input type="checkbox"> Checkbox <br>
<input type="checkbox"> Checkbox <br>
</fieldset>

So the first input type with the .checkall class is going to be the input that, when checked, will also check all the other boxes that are in that fieldset. The jQuery for achieving this effect is as follows:

$(function () {
$('.checkall').click(function () {
$(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
});
});

Again, this code will only apply the check all functionality to boxes within the fieldset of the check all button. If there are other checkboxes within a different fieldset, they won’t be affected by the checking of this particular check all button (but if the code of another fieldset is exactly the same, checking that check all button will check all of the checkbox input fields in that particular fieldset). The code can be changed and customized to reflect your own classes.