Jquery toggle hide show question

What's the most efficient way to cut this?

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

      

and something will change to your answer if another parameter is added with else if

0


a source to share


3 answers


$('#myid').click(function() {
        $('#a,#b').toggle();
});

      



+6


a source


I'm going to assume that you are trying to map all elements to the "img" class.

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

      

To allow multiple identifiers



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

      

You can also check not equal by id

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

      

+4


a source


Why are you checking the id of the element inside the click event? If you want this particular element to handle this event, select it and bind an event handler to it.

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

$('#myid').click(function(){
    $('#a').toggle();
    $('#b').toggle();
})

      

0


a source







All Articles