jQuery Dynamic Slider Scroll Function

Discussion in 'HTML & Website Design' started by Ian Blom, Jul 12, 2015.

  1. #1
    Hi

    I'm looking for a way to change my current jQuery code which currently slides though two div containers and would like the navigation to be more dynamic/generic. So basically, if I add more <li> links and content containers, then the jQuery code shouldn't have to be modified as it needs to be setup in a way to automatically adapt. Instead of having to hardcode each <li>'s click function for each section, the code must know which <li> has been clicked and which content should be displayed.

    $('.one').on('click',function(){
    $('#content-container').css({'margin-left':'0px'});
    });
    $('.two').on('click',function(){
    $('#content-container').css({'margin-left':'-100%'});
    });

    Please note that my container has a width of 100% and works perfectly as it is right now. See working example on JSFiddle:

    http://jsfiddle.net/ianblom/gv4qf1u5/1/

    I'm new to jQuery and would appreciate any help in this regards.

    Thanks!!
     
    Ian Blom, Jul 12, 2015 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    Just create an ID on the clicked li-item that corresponds with a value on the content-container.
    Also, why are you using classes for the li-items instead of IDs? That can become troublesome if you have more instances of the class elsewhere (which is also the only reason for having a class in the first place). Also, why the "on"-method? Do you add these li-items dynamically? If not, there's no reason using "on", just use "click" - something like this:
    
    $('#menulist li').click(function() {
      var clickedID = $(this).attr('id');
      $('.content_container').css({'margin-left':'-100%'});
      $('#content_'+clickedID+'').css({'margin-left':'0px'});
    })
    
    Code (markup):
    That should make sure that all the not-clicked items disappear, and the actual clicked item shows up.
    Here's an example: http://jsfiddle.net/gv4qf1u5/2/
     
    PoPSiCLe, Jul 12, 2015 IP