tags:

views:

976

answers:

3

what is the most efficient way to shorten this?

$('.img').click(function(e) {
    if ($(this).attr('id') == 'myid') {
        $('#a').hide();
        $('#b').show();
    } else {
        $('#a').show();
        $('#b').hide();
    }
});

and does anything change to your answer if another option is added with an else if

A: 

Why are you checking for the element id inside the click event? If you only want this specific element to handle this event then select it and bind the event handler to it.

Assuming that at any time there is either #a or #b showing:

$('#myid').click(function(){
    $('#a').toggle();
    $('#b').toggle();
})
Nadia Alramli
+3  A: 

I'm going to assume your trying to match all elements with a class called "img".

$(".img[id='myid']").click(function() {
        $('#a,#b').toggle();
});

To allow for multiple IDs

$(".img[id='myid'], .img[id='myid2']").click(function() {
        $('#a,#b').toggle();
});

You can also check for not equals on the id

$(".img[id!='someid']").click(function() {
        $('#a,#b').toggle();
});
gradbot
+4  A: 
$('#myid').click(function() {
        $('#a,#b').toggle();
});
duckyflip