'Detecting clicks outside an element with 'on' event?
I need to detect clicks outside the element with id 'proplist'. However, I already have an 'on' event function that detects value changes of an input. I tried to access the form-key value from the mouseup event, but I it didn't return any data. How can I get the value of form-key after detecting clicks outside the element?
$('#plusData').on("blur", "input[id^=form-key]", function(){
console.log($(this).val());
$(document).mouseup(function (e) {
if ($(e.target).closest("#proplist").length === 0 ) {
console.log($(this).val());
}
});
});
html code
<div id="proplist">
<div id="plusData">
<div class="form-group form-group-extraData" id="box" style="width: 100%;">
<input type="text" class="form-control" id="form-key1" name="key" >
<input type="text" class="form-control" id="form-content1" name="content" >
<input type="button" class="btn btn-alt-primary" value="+" onclick="addTextbox()">
</div>
</div>
</div>
Solution 1:[1]
As far as I know, you can't really modify the outside element from a css selector.
But you can just add another event listener for the parent of this element, or add such wrapper for that. CSS pseudo selector :has() maybe a way out for this.
For example, I made 2 wrappers in the snippet below, one has a child #proplist and the other one doesn't.
$('.wrapper:has(#proplist)').click(e => {
console.log(e.target.classList.value);
e.target.classList.toggle('red');
});
.wrapper {
background: none;
height: 100px;
border: 1px solid #000;
}
.wrapper.red {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div id="proplist">
<div id="plusData">
<div class="form-group form-group-extraData" id="box" style="width: 100%;">
<input type="text" class="form-control" id="form-key1" name="key" >
<input type="text" class="form-control" id="form-content1" name="content" >
<input type="button" class="btn btn-alt-primary" value="+" onclick="addTextbox()">
</div>
</div>
</div>
</div>
<div class="wrapper">
<h1>Not having proplist</h1>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dhana D. |
