0

I'm new to javascript/jQuery and I'm trying to find the smartest way to trigger an event based on whether a id is active or not :

<ul class="tabs">
<li id="1" class="active"><a href="#"></a></li>
<li id="2"><a href="#"></a></li>
<li id="3"><a href="#"></a></li>
<li id="4"><a href="#"></a></li>
</ul>

It becomes a bit more difficult as the rule is as follow:

if id=1 is active, trigger alert("A") if id=2 is active trigger alert("B") if id=3 is active trigger alert("C") if id=4 is active trigger alert("D")

What function could I use to map 1 with A, 2 with B etc. ?

Thanks !

3
  • 1.Don't use numbers as IDs Commented May 31, 2013 at 21:23
  • You can add a click listener to your lis , call a method and in the method , if the id has a class , give an alert statement Commented May 31, 2013 at 21:25
  • good tip but i'm more concerned about how to map the values: 1 with A, 2 with B etc. Commented May 31, 2013 at 21:27

3 Answers 3

0
var functionsMap = {
    "id1": function() { ... },
    "id2": function() { ... },
    ...
};

$('.tabs li').on('click', function() {
    var id = $(this).attr('id');
    functionsMap[id]();
});

Of course add check if function exists for element with such id, etc...

4
  • Thanks, but the key here is the li being active, not the "click". Can we make it independent from the click event ? Commented May 31, 2013 at 21:40
  • Of course you can, just run such code: functionsMap[ $('.tabs .active').attr('id') ]() Commented May 31, 2013 at 21:45
  • Good thanks ! And final silly question: when you write "id1": function() { ... },, what should ... be replaced with ? Commented May 31, 2013 at 21:49
  • there should be any logic you want. For example alert('A') for first functions, alert('B') for second one, some animation for third, etc. Commented May 31, 2013 at 21:57
0
var call_arr = ['a', 'b', 'c', 'd'];

$('click a random button').click(function(){
    var ind = $('li.active').index();
    alert(call_arr[ind]); 
});
2
  • That's good however there are different buttons to make the li active. Can this be independent from the click event ? Commented May 31, 2013 at 21:38
  • @user2441947 you can wrap it in a function and call the function.
    – Spokey
    Commented May 31, 2013 at 21:53
0

Try this.

var data = ['a', 'b', 'c', 'd'];

$('.tabs li').click(function(){
    alert(data[$(this).index()].toUpperCase()); 
});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.