Reputation: 1020
Following is the code
(function(window){
var form = document.getElementById('form_element'),
form2 = document.getElementById('form_element2'),
container = document.getElementById('container');
window.addEventListener('mouseup', getAlert);
function getAlert(event) {
if(event.target === form) {
alert('I clicked on a form');
}
}
form2.addEventListener('click', function() {
container.innerHTML = '<h1>I am however working</h1>';
});
})(window);
#container {
height:400px;
width:400px;
background:red;
}
#form_element {
display:inline-block;
}
<form action="" id="form_element">
<input type="text" placeholder="Enter here..."/>
</form>
<form action="" id="form_element2">
<input type="text" placeholder="Enter here..."/>
</form>
<div id="container">
<h2>Something goes here</h2>
</div>
Could you help me with this, with some explanation? Does this differ in jquery selector?
I am stuck with such small situations. Could you please help me work it out.
Thanks
Upvotes: 1
Views: 198
Reputation: 7315
The problem is that the target
when the mouse goes up
is the input element
and not the form
Here are some ways to solve your problem
Check if the target
is the input element
window.addEventListener("mouseUp", getAlert);
function getAlert(event) {
if (event.target === form.firstElementChild) {
alert('I clicked on a form');
}
}
Add the listener
to the form
so that there is no need to check anything
form.addEventListener("mouseUp", getAlert);
function getAlert(event) {
alert('I clicked on a form');
}
Check if the target
is the form
OR if the target
is an element
of the form
window.addEventListener("mouseUp", getAlert);
function getAlert(event) {
if (event.target === form || form.contains(event.target)) {
alert('I clicked on a form');
}
}
Use CSS
to add some padding
to the form
so you can have space to click the form
without clicking the input
#form_element {
padding: 20px;
}
Use CSS
to make the input element
"invisible" to the mouse
#form_element>input {
pointer-events: none;
}
Upvotes: 1