0

I have a list, and I want to run a switch statement for whether or not the clicked element has a certain class - then hide all the others.

Here's what I have, but the switch statement doesn't pick up the variable set with the click.

<ul>
  <li class="all"><a>Show all</a></li>
  <li class="design"><a>Design</a></li>
  <li class="dev"><a>Development</a></li>
  <li class="ux"><a>UX</a></li>
  <li class="print">Print</a></li>
</ul>

and:

$(function() {
$('a').click(function() {
    var wrkType = $(this).parent().attr('class')

    //alert(day) // alerts !
    });
});

 switch (wrkType)
{
case 'dev':
  alert('yahmon!')
  if (!$('li').hasClass('dev')) { $('li').fadeOut(300); }
  break;
case 'all':
  //All things on
  break;
} 

How can I achieve this?

Secespitus
  • 710
  • 2
  • 14
  • 22
colin
  • 43
  • 1
  • 7

2 Answers2

1

If you are accessing the variable in other function,Make your workType variable global.Now it is local to the click callback function.

If you want to run in the same click event callback,Move your switch code to inside the callback function.

like this

$('a').click(function() {
   var wrkType = $(this).parent().attr('class')
   switch(wrkType ){
      case 'dev':
   --  

 --  
   }
});
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

This should work

$(function() {
   $('a').on('click', function() {
    var wrkType = $(this).parent().attr('class')
     WorkType(wrkType);
    //alert(day) // alerts !
    });
});

 function WorkType (wrkType) {
 switch (wrkType)
 {
    case 'dev':
      alert('yahmon!')
      if (!$('li').hasClass('dev')) { $('li').fadeOut(300); }
    break;
    case 'all':
      //All things on
    break;
}
}

I would suggest to use on instead of click.

26ph19
  • 773
  • 9
  • 17
  • Is that switch condition no need to keep inside if click ? – Suresh Atta Aug 30 '13 at 18:13
  • thanks for showing me i can call the switch from inside the click function. it's confusing to me to have the name wrkType so many times because i'm not sure what each is doing. why is the use of on better? – colin Aug 30 '13 at 18:42
  • [Post](http://stackoverflow.com/questions/9122078/difference-between-onclick-vs-click). Check the answer which has high votes. If my answer is informative then at least give it up vote or better accept this as answer. – 26ph19 Aug 30 '13 at 18:45