Home > database >  How can I recognize a click is inside a texarea or is outside? [closed]
How can I recognize a click is inside a texarea or is outside? [closed]

Time:09-16

this is my html

<textarea>
   <p>some text</p>
</textarea>

And I have a lot of these textarea in my code

When there is not any HTML tag inside the textarea I can get my expected textarea, but when there is a p tag inside the textarea, my code get just the p tag and cannot get the parent

body.click((evt) => {
    console.log($(evt.target));                      // return the p tag
    console.log($(evt.target).parent());             // return undefined
    console.log($(evt.target).parents('textarea'));  // return undefined
    console.log($(evt.target).nodeParent);           // return undefined
}

CodePudding user response:

You can the jQuery .is() method with e.target as in the following demo. Please note that in this demo you have to click within the form for the click event to trigger.

$(function() {
    const textarea = $('#bio');
    $('form').on('click', function(e) {
        console.log( e.target );
        if( $(e.target).is(textarea) ) {
            console.log( 'You clicked inside the textarea' );
        } else {
            console.log( 'You clicked outside the textarea' );
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>

<input type="text" name="name" placeholder="Full Name"><br><br>

<input type="email" name="email" placeholder="Email"><br><br>

<textarea name="bio" id="bio" placeholder="BIO"></textarea>

CodePudding user response:

Maybe you should give an id to your textarea and bind the click event on it ?

const textarea = document.getElementById('myTextarea');
textarea.onclick = (ev) => console.log(ev);

fiddle

  • Related