I have a text area, button to save the text that is type inside the text area and some other stuff on the page.
I want to click outside of the body and save the text that I type inside the text area; my body should act as button.
My problem is it does save the information but it affects everything that I have on my page e.g. wherever I click, it saves and I want it not to save when I click some other button – it should focus only outside the element.
What should I do to focus only outside the element because I even try function called stopPropagation.
var text_a = document.getElementById("myTextarea");
var btn_saveComment = document.getElementById("submit2");
function saveComments() {
text_a.style.display = "block";
$("#comment").text($(text_a).val());
var g = document.getElementById("checks5");
g.checked = true;
g.disabled = false;
$("#checks5").css({
backgroundColor: "#C40929"
})
}
document.addEventListener("click", function(e) {
e.stopPropagation();
text_a.style.display = "block";
$("#comment").text($(text_a).val());
var g = document.getElementById("checks5");
g.checked = true;
g.disabled = false;
$("#checks5").css({
backgroundColor: "#C40929"
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div class="wrapper">
<input type="checkbox" class="check_ticks" id="checks5">
<label for="checks5"></label>
</div>
<p id="comment" class="text_info"></p>
<textarea id="myTextarea" rows="5" cols="30" class="myText"></textarea>
<button class="dropbtn" id="submit2" onclick="saveComments()">Save Comment</button>
2
Answers
You can simply add
onBlur
attribute to the text area. Like this:See demo below:
Using simple vanilla Javascript you can use the
event
to aid the process of using the document Body to work as the button in the original code by inspecting theevent.target
andevent.currentTarget
properties. When the event listener is bound to the body ( as below ) the currentTarget is the body element itself rather than any child element so that allows you to process the click on that itself quite easily.( css to make this easier to observe within the snippet )