webmonkey237 webmonkey237 - 1 month ago 11
jQuery Question

jQuery sliding panel for multiple instances

I have a piece of code that works great, you can click one button which triggers one sliding div.

$(document).ready(function () {
$('div.shareTab').on('click', function () {
$('.sharePanel').animate({
'width': 'show'
}, 1000, function () {
$('.shareFade').fadeIn(100);
});
});
$('.shareClose').on('click', function () {
$('div.shareFade').fadeOut(100, function () {
$('.sharePanel').animate({
'width': 'hide'
}, 1000);
});
});
});


I have a different project which requires multiple buttons and multiple panels, is there a better way to write my script rather than just copy/pasting the script multiple times.

I have supplied a fiddle below to show what i'm trying to achieve, at the moment clicking on one of the names opens all the panels at once.

FIDDLE

Answer

You can make that using data attribute and some tricks on jquery:

$(document).ready(function() {
  $("a.shareTab").each(function(index, item) {
    $(this).on("click", function() {
      $('.sharepanel' + $(item).data("panel")).animate({
        'width': 'show'
      }, 1000, function() {
        $('.sharepanel' + $(item).data("panel") + ' .shareFade').fadeIn(100);
      });
    });
  });

  $('.shareClose').on('click', function() {
    $('div.shareFade').fadeOut(100, function() {
      $('.sharePanel').animate({
        'width': 'hide'
      }, 1000);
    });
  });
});

This is fiddle fork: fiddle

Comments