Reputation: 127
I have a textarea
for the user to type something and it has a cancel
and a submit
button as part of it.
How can I make it so that the cancel
and submit
button only appears when the user clicks inside the textarea
? (using javascript, no jquery please)
I have attempted using this javascript function:
function setButtons(writingtext) {
if (writingtext) {
document.getElementById('cfm').style.display = 'block';
document.getElementById('cancel').style.display = 'block';
}
else {
document.getElementById('cfm').style.display = 'none';
document.getElementById('cancel').style.display = 'none';
}
}
When the user clicks the text area, it would be onClick="setButtons(True)"
-> displays the buttons.
I'm not sure if this is the right approach here. Sorry, really new to this.
Any help would be appreciated!
Upvotes: 0
Views: 1033
Reputation: 113
You should use
onfocus="setButtons(this)"
instead of onClick
function setButtons(writingtext) {
document.getElementById('cfm').style.display = 'block';
document.getElementById('cancel').style.display = 'block';
}
Upvotes: 0
Reputation: 1014
You can just assign an id to the textarea for example text
and then use
document.getElementById('text').addEventListener('focus', function(){
document.getElementById('cfm').style.display = 'block'
document.getElementById('cancel').style.display = 'block'
})
// Hide when blur (when not focused)
document.getElementById('text').addEventListener('blur', function(){
document.getElementById('cfm').style.display = 'none'
document.getElementById('cancel').style.display = 'none'
})
Upvotes: 0
Reputation: 1017
This is only a simple example to show the buttons on focus. If you want to hide them, I think you will be able to manage that solution.
If all you want to do is show the buttons when the text area is focused, use the CSS-only solution. However, I'm guessing you'll want to keep them for a bit or do some extra pre-processing before the submit, in which case you should use the javascript option.
document.querySelector("#textarea").addEventListener("focus", function() {
document.querySelector("#submit").style.display = "block";
document.querySelector("#cancel").style.display = "block";
});
button {
display: none;
}
<textarea id="textarea"></textarea>
<button id="submit">Submit</button>
<button id="cancel">Cancel</button>
Upvotes: 0
Reputation: 9012
You have control over your html you can do it with just css
sniping the next sibling at :focus
like this:
div {display:none;}
textarea:focus + div {display:block;}
<textarea name="" id="" cols="30" rows="10"></textarea>
<div>
<input type="submit">
<input type="submit">
</div>
Upvotes: 1