Hide buttons on click in textarea

I am working on a user input interface which includes a textarea for typing, along with a cancel and submit button.

Is there a way to show the cancel and submit buttons only when the user clicks inside the textarea? (I prefer using vanilla JavaScript instead of jQuery)

I have tried implementing the following JavaScript function:

function controlButtons(userInput) {
    if (userInput) {
        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';
    }
}

To trigger the display of buttons upon clicking inside the textarea, I used onClick="controlButtons(True)".

I'm still unsure whether this is the best approach. Any suggestions from experienced developers would be greatly helpful!

Answer №1

Take charge of your HTML by utilizing CSS to target the next sibling when focused, as demonstrated below:

div {visibility: hidden;}
textarea:focus + div {visibility: visible;}
<textarea name="" id="" cols="30" rows="10></textarea>
<div>
  <input type="submit">
  <input type="submit">
</div>

Answer №2

Here is a straightforward illustration to demonstrate how buttons are displayed when focused. Should you wish to conceal them, I believe you can find a solution for that.

If your goal is simply to reveal the buttons upon focusing on the text area, opt for the CSS-only approach. However, if you intend to retain them temporarily or perform additional actions before submitting, it would be wise to utilize 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>

Answer №3

To display certain elements when a textarea with the id text is focused, you can simply use event listeners in JavaScript.

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'
})

Answer №4

It is advisable to utilize onfocus="setButtons(this)" in place of onClick

function setButtons(writingtext) {
    document.getElementById('cfm').style.display = 'block';
    document.getElementById('cancel').style.display = 'block';
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine the position of an HTML list using Xpath by considering additional criteria

After investigating a workaround for this unresolved question, I am now facing a new challenge. I am curious if it is possible to retrieve the list position from HTML based on certain search criteria? This would enable me to reconstruct the xpath of the ...

Retrieving a specific item from a JSON object within the AJAX success function

Utilizing the ajax call below to retrieve a JSON object from the server side (PHP) $.ajax({ url: endpoint, method: "POST", data: { id : userId }, dataType: "json", success: function(result) { $("#itemName").val(result.itemNa ...

Struggles with Aligning CSS Layout

I'm encountering some challenges with the layout of my webpage, particularly with alignment. Here are the issues I'm facing: The login section doesn't fit well in the header and lacks proper alignment. I aim to replicate the design from ...

obtaining Json format from an array: a comprehensive guide

Hey there, I am looking to convert my array into JSON format. Currently, my array structure looks like this: Array[0] abc: Array[1] 0: "English" length: 1 abc1: Array[2] 0: "English" 1: "Urdu" length: 2 Here is the structure that I want in JSON using Jav ...

Next JS Event Listener Failing to Detect Scroll Events

Currently, I am attempting to change the state and display a shadow in the navigation bar when the user scrolls, but for some reason it is not detecting the event. I am working with nextJS 13 and tailwind css. const [shadow, setShadow] = useState(false) ...

Tips for keeping certain webpages from showing up in Google search results

I recently launched a website that allows users to create their own profiles. The problem is, when someone links to their profile from their website or blog, it ends up showing in Google searches for my site. Unfortunately, the only person who has done thi ...

Unable to interact with web element

When using selenium, I have a web element that I want to select. The WebElement.IsDisplayed() method returns true, but I am unable to perform the webelement.click() operation. port_dimension = canvas.find( By.xpath( "//*[local-name() = 'rect'][ ...

There was an error in the syntax: JSON parsing error, an unrecognized token '<'

Having trouble with a syntax error: JSON parse error due to an unrecognized token '<'. One page is functioning properly with the same code, while another is displaying this error. I am unable to identify my mistake. Front-end code: const getd ...

Showing the SQL table data output

Attempting to present a new table based on the SQL query result. Below is the initial table code shown when the user first loads the page. TABLE: <form action="walkthroughs.php" method="POST"> Platform: <input type="text" name="platform" ...

Webpage featuring tabs aligned horizontally

Can anyone guide me on setting up horizontal tabs similar to the design in this image: https://i.sstatic.net/ewXO4.png? Below is the code snippet: <label class="formlabel">Title 1:</label> <div id="radio_form"> <label><inpu ...

Exploring different techniques to display images in React JS using mapping or looping?

This is my custom JavaScript file that includes images for my project. import React, { Component } from 'react'; import './Stopka.css'; class Stopka extends Component { render() { return ( <div clas ...

Creating a Prismoid Shape Using Three.js

Currently, I am utilizing Three.js and my objective is to construct a pyramid shape with its apex removed. The base of the pyramid should be a rectangle instead of a square, while the top should also be a rectangle, but not in equal proportions. Here is a ...

Iterate over the keys within a JSON array that begin with a certain key name

Is there a more efficient way to dynamically loop through keys in a JSON array starting with 'option' and either loop through them all or set a maximum limit? Currently, I am using the following approach: $.each(shopifyProductJSON.variants, fun ...

Retain chosen option after form submission in PHP/HTML

I have seen many questions asked about this before, but despite trying various solutions here, none seem to work for me. I am populating a list from my mysqli database: <select multiple="multiple" name="formCountries[]" size="5" id="keuzeproduct"> ...

Unable to save array in global variable using Ajax, constantly receiving undefined

I'm attempting to store an array obtained from an ajax call in a global variable so that I can access it later, but I keep encountering an undefined error. <script> var items = []; function add(value){ items.push(value); ...

What is the reason behind the success of 'as' in ngFor compared to '='?

<tr *ngFor = "let item of list; let i = index;"> An issue arises with the code above: The error message reads: Type 'number' is not assignable to type 'string'. td [ngModelGroup]="j" #temp="ngModelGroup ...

Issues with displaying form/button glyphicon when using a fixed table header in Bootstrap

I have a situation where I have a table with a fixed header. In one of the columns, there are delete buttons within a form. The table structure is as follows: <div class="panel panel-default table-responsive fixedHeader"> <!-- Table --> &l ...

Creating an automated CRUD API using Node.js, Express, and Mongoose

In the realm of Python, we have often relied on tools like tastypie or Django-Rest-framework to build Rest APIs. After delving into Felix Geisendörfer's article Convincing the boss, one particular statement caught my attention: Node.js truly exce ...

Retrieve data from a REST API in a dynamic manner without manually specifying the table structure in the HTML code

I am looking to retrieve JSON data via a post request from a REST API: http://localhost/post1 param1='1' The response will look like this: { "json_table": [ { "date": 123, "test": "hello2" }, { "date": 19, ...

Operating on Javascript Objects with Randomized Keys

Once I retrieve my data from firebase, the result is an object containing multiple child objects. myObj = { "J251525" : { "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c3823212 ...