Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop event propagation by clicking inside input element

I am encountering a weird problem here, I have a div having an click event attached to it, and a input having on-blur event and button having click event attached to it.


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div onClick='div()'>
<input onBlur='input()' />
<button onClick='button(event)'> ABCD </button>
</div>
</body>
</html>

Here are the functions that gets called when buttons are clicked.

function input(event){
    console.log('input')
    event.stopPropagation();
}

function button(event) {
  console.log('button')
  event.stopPropagation();
}

function div(){
  console.log('div')
}

The problem that I am encountering here is that, if I click inside the input box then it is logging what is inside the div function, I tried event.stopPropagation(), but it doesn't seem to work is there any way to make it work? i.e - not logging what is inside div on clicking the input.

Here is a Bin for the same.

like image 734
Divyanshu Rawat Avatar asked Sep 24 '19 09:09

Divyanshu Rawat


1 Answers

You have to set stop propagation for input click not on blur , so the div click will not be propagated :

see below snippet

function input(){
	console.log('input')
    event.stopPropagation();
}

function inputStopPropagation() {
   event.stopPropagation();
}

function button(event) {
  console.log('button')
  event.stopPropagation();
}

function div(){
event.stopPropagation();
  console.log('div')
}
<div onClick='div()' style="padding:5px; background :green">
<input onBlur='input()' onClick='inputStopPropagation()' />
<button onClick='button(event)'> ABCD </button>
</div>
like image 117
Spring Avatar answered Sep 26 '22 06:09

Spring