S. S. Rawat
S. S. Rawat

Reputation: 6131

hide and show image on button click

I have two image and two button in a div, Now process is when i click on button 1 then image 1 show same as in button 2.. now my problem is i want both image hide when i click in any part of body.. Now my problem is when i click on body it will hide but not able to show images on button click.

Fiddle Here

HTML

<input type='button' id='btn1' value='button1'>
    <img src="abc.jpg" id='img1'>
        <input type='button' value='button2' id='btn2'>
    <img src="abc.jpg" id='img2' >

Js

$('#btn1').click()(function(){
       $('#img1').show();
                       $('#img2').hide();   
                  });
$('#btn2').click()(function(){
       $('#img2').show();
                       $('#img1').hide();   
                  });

$('body').click()(function(){
 $('#img1').hide();   
     $('#img1').hide();   
});

Upvotes: 0

Views: 9343

Answers (2)

Krishna
Krishna

Reputation: 1985

try this

 $('body').click(function(e) {
        var target = $(e.target);
        if(!target.is('#btn1') || !target.is('#btn2')) {
           $('#img1').hide();   
         $('#img1').hide();
        }
    });

Upvotes: 0

j08691
j08691

Reputation: 208002

Try:

$('#btn1').click(function (e) {
    e.stopPropagation();
    $('#img1').show();
    $('#img2').hide();
});
$('#btn2').click(function (e) {
    e.stopPropagation();
    $('#img2').show();
    $('#img1').hide();
});
$('body').click(function () {
    $('#img1,#img2').hide();
});

jsFiddle example

You were using the click function incorrectly, plus your click events on the buttons were also bubbling up the DOM to the event you placed on the body.

Upvotes: 2

Related Questions