Thursday, March 29, 2012

jQuery Trigger custom parameters

So I just found out that you can pass custom parameters to jQuery's trigger(), which greatly simplifies automating UI actions.

Say you're building a really basic carousel:

<ul class="carousel">
  <li><img src="slide1.jpg" /></li>
  <li><img src="slide2.jpg" /></li>
  <li><img src="slide3.jpg" /></li>
</ul>
<button id="next">Next</button>

$.fn.carousel = function(options) {

  //hide all the slides, except the first one
  this.children().hide().first().show()
  
  var self = this
  $(options.next).click(function(e) {
    e.preventDefault()

    //move first slide to end of list and hide it
    self.children().first().appendTo(self).hide()

    //show new first slide
    self.children().first().show()
  })
  
}

$(".carousel").carousel({next: "#next"})

And say you want to make it rotate automatically every 10 seconds.

var animation = setInterval(function() {
  $("#next").trigger("click")
}, 10000)

BUT, you want to make it stop once a user clicks the button to go next. What now?

Custom parameters

You basically just want to differentiate between a real user clicking, and the click event that is fired programmatically from the setInterval. We can use custom parameters to do this fairly elegantly:

var animation = setInterval(function() {
  $("#next").trigger("click", [true])
}, 10000)

$.fn.carousel = function(options) {

  //hide all the slides, except the first one
  this.children().hide().first().show()
  
  var self = this
  $(options.next).click(function(e, continueAnimation) {

    if (!continueAnimation) clearInterval(animation)

    e.preventDefault()

    //move first slide to end of list and hide it
    self.children().first().appendTo(self).hide()

    //show new first slide
    self.children().first().show()
  })
  
}

$(".carousel").carousel({next: "#next"})

A regular click event only passes the event object as a parameter to the callback function, so the continueAnimation variable is undefined in that case. When triggering the event programmatically, we can pass the value true and run code conditionally based on that.

So that's it.

No comments:

Post a Comment