0

I have a webpage with several hidden divs. I have them set up so that when an image is clicked, they will display and if the image is clicked again, they hide. The problem is, I need to hide them if they're visible and any part of the page is clicked. I've searched high and low and have found some suggestions but have yet to find one that works. Can anyone help?

Mark Highfield
  • 443
  • 3
  • 9
  • 24

3 Answers3

1
$(window).click(function() {
    $('img').hide();
});

Very simple example

James Coyle
  • 9,922
  • 1
  • 40
  • 48
0

I usually bind a document.click event to listen for a click outside and then remove it when the window is closed.

// in function after your image shows up.
document.click = hideImage;
// other code to hide image when image is clicked

// in function after your image is hidden.
document.click = null;

If you're using jQuery it's easier because you can namespace your events for safe add and removal.

// in function after your image shows up.
$(document).bind('click.imagehide', hideImage);
// other code to hide image when image is clicked

// in function after your image is hidden.
$(document).unbind('click.imagehide');

This method is safer so you don't interfere with other click events bound to the document.

earl3s
  • 2,393
  • 1
  • 23
  • 24
0

What you need to do is prevent event bubbling. If you are using jquery you can do:

$(document).on ('click', function () { $('div').hide (); });
$('img').on ('click', function (e) { e.stopPropagation (); });

Remeber to change the selectors to fit your needs.