Pregunta

I need to give users the option to choose view modes between List-view, Grid-view, and Full-view. The basic structure is simple, something like this:

<ul>
    <li><a href="#">List Toggle</a></li> 
    <li><a href="#">Grid Toggle</a></li> 
    <li><a href="#">Full Toggle</a></li> 
</ul>

<div id="wrap">
<div id="list-view">
    <div class="line">lorem line</div>
    <div class="line">lorem line</div>
    <div class="line">lorem line</div>
</div>

<div id="grid-view">
    <div class="box">lorem box</div>
    <div class="box">lorem box</div>
    <div class="box">lorem box</div>
</div>

<div id="full-view">
    <div class="full">full lorem</div>
    <div class="full">full lorem</div>
    <div class="full">full lorem</div>
</div>
</div>

Here is a jsfiddle I started with list-view set as visible and others hidden:

http://jsfiddle.net/eTb5C/13/

Here is one I was thinking of implementing, but need it for 3 options.. http://jsfiddle.net/mgNQy/2/

Basically, if you click on a view mode, the current view mode will fade out and the selected view mode will fade in.

I would also like to add a cookie to remember the user's preference if possible, but I don't know how to do that. I am pretty new to jQuery hopefully my questions aren't too basic.

¿Fue útil?

Solución

Acutally there is nothing special, you have only three tabs ( list, grid, full ). First, i recommend to you to follow the mark-up below :

   <ul class="tabs js-view-mode">
      <li><a href="#list">List</a></li>
      <li><a href="#grid">Grid</a></li>
      <li><a href="#full">Full</a></li>
    </ul>

    <section id="viewMode">
      <div id="list">here is list mode content</div>
      <div id="grid">here is grid mode content</div>
      <div id="full">here is full mode content</div>
    </section>

As you can see, on tabs, inside <a href=""> class i put the id's for what we want to show. This is safe and easy because the script will not confuse what he has to show.

Also in html you must load jquery library and jquery-cookie ( you can avoid loading this plugin following the documentation for javascript-cookies ). Better load them before </body> tag to get a faster loading time for page.

The jQuery code for what you want looks like :

$(document).ready(function(){
  var wrap = $('#viewMode'),
      viewMode = $.cookie( 'view-mode' );
  wrap.children().hide();

  $('.js-view-mode').on( 'click', 'a',function( e ){
    e.preventDefault();
    var t = $(this),
        type = t.attr('href');

    $(type).fadeIn()
      .siblings().fadeOut();

    viewMode = $.cookie( 'view-mode', type );

  });

  if ( viewMode ) {
    $('.js-view-mode a[href='+ viewMode +']').trigger('click');
  } else {
    $('.js-view-mode li:first a').trigger( 'click' );
  }

});

You can see a live test here

Edit : JS Fiddle v2 ( add active clas + delay fadeIn/Out + return on clicking active item )

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top