how to bind 2 elements in jquery on click function

Viewed 1069

For closing a modal with the class submitmodal i use this code and it works fine.

$('.submitmodal').click(function() {          
      window.location.hash='close';
});

For click on the body somewhere i use this:

$('body').click(function() {          
      window.location.hash='close';
    });

How can i merge them together?

I tried this but it does not work

$('.submitmodal', 'body').click(function() {          
      window.location.hash='close';
    });
6 Answers

Try

(".submitmodal, body").click(function() {          
      window.location.hash="close";
});

The selectors have to be in the same string, seperated by a comma.

Try this :

    $(document).on("click",'body',function(){
       window.location.hash='close';
    })

This should do it

$('.submitmodal, body').click(function() {          
    window.location.hash = 'close';
});

You can use Multiple selector using first selector, second selector

$('body,.submitmodal').click(function() {          
          window.location.hash='close';
        });

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.

$("body, .submitmodal").click(function() {          
      window.location.hash="close";
});

For More help see this : multiple-selector I hope it helps you :), Thanks.

This should solve your issue:

$('.submitmodal, body').click(function() {          
      window.location.hash='close';
});

But the problem I see is that when you click anywhere over the body you are closing your modal and that includes when you click over the element that opens itself. So I would suggest you to write something like that:

$('body, .submitmodal').click(function(e) {  
      if (e.target !== this) return;  //prevents body's child elements from being affected
      window.location.hash='close';
});

I've done some tests and apparently 'this' references to the first selector (body) which is fine for this situation.

Related