jeff
jeff

Reputation: 1020

event.target does not work for properly in jQuery code

I am stuck with the following simple code.

$(function() {

	'use strict';
	
	function header() {
		
		var openButton = $('.search_button'),
			  box = $('.box'),
			  closeButton		= $('.close');
		
		box.hide();

		function init() {
			
			initEvents();
		}
		
		function initEvents() {
			openButton.on('click', openBox);
			$(document).on('keyup', function(event) {
				if(event.keyCode === 27) {
					box.slideUp('normal');
				}
			});
		}
		
		function openBox(event) {
			
			if(event.target === closeButton[0]) {
				box.hide();

			} else if(event.target === openButton[0] || $(event.target).closest(box).length) {
				box.show();	
			} 
			
			else {
				box.hide();
			}
		}
		
		init();
	}
	
	header();
});
.box {
  width:500px;
  height:500px;
  background-color:red;
  position:relative;
}

.close {
  width:80px;
  height:80px;
  background-color:orange;
  position:absolute;
  top:0;
  right:0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header_search">
	<form action="search.php" method="post">
		<input type="text" placeholder="" id="main_search" class="search_button">
	</form>
</div>

<div class='box'>
  <div class='close'></div>
</div>

My intension is that, when I click outside the DIV, it closes and the 'close' DIV on click closes the red main div.

The code, slidesDown the box div and escape key slideup as well.

But close and clicking outside to close the red div does not work.

Could someone assist me with the code with some explanation

Thanks and regards

Jeff

Upvotes: 2

Views: 104

Answers (1)

Yuri Pereira
Yuri Pereira

Reputation: 1995

You are using the event handler click only in the .search_button, you have to use it in your body.

    function initEvents() {
        $(body:not('#header_search')).on('click', openBox);
        $(document).on('keyup', function(event) {
            if(event.keyCode === 27) {
                box.slideUp('normal');
            }
        });
    }

Upvotes: 1

Related Questions