Switching the visibility of multiple textareas from block to none

I am currently exploring ways to make one text area disappear while another one appears in its place.

With limited knowledge of Javascript and just starting my journey into HTML and CSS, I am reaching out to the forum for assistance or guidance on the right path.

I have included a snippet of the code below for clarity.

On clicking "2.svg," it should change the display property of "textarea.one's and three's" from "block" to "none."

Clicking "3.svg" should toggle the visibility of "textarea.two's and one's" from "block" to "none."

Similarly, selecting "1.svg" should switch the display status of "textarea.two's and three's" from "block" to "none."

I hope this explanation is clear, and I apologize if seeking full code assistance without attempting on my own is not allowed on this platform.

Thank you in advance to anyone who takes the time to read this!

<div>
<img id="header1" src="/1.svg" alt="Open Menu" class="menu">
<img id="header1" src="/2.svg" alt="Open Menu" class="menu">
<img id="header1" src="/3.svg" alt="Open Menu" class="menu">
</div>

<div class="textniz">
<textarea class="one" id="myInput" name="myInput" readonly>
Line one
Line two
Line three</textarea>
</div>

<div class="textniz">
<textarea class="two" id="myInput" name="myInput" readonly>
Line four
Line five
Line six</textarea>
</div>

<div class="textniz">
<textarea class="three" id="myInput" name="myInput" readonly>
Line seven
Line eight
Line nine</textarea>
</div>

Answer №1

Check out this link for more information: https://www.w3schools.com/jsref/prop_style_display.asp

To modify the display property of an element, you can do so by accessing it in the following way:

document.querySelector("myelement").style.display = "theValueIWant";

Make sure to familiarize yourself with different selectors.

If you want to change the display property of textarea one and three to none when clicking on 2.svg, you can achieve this using:
First select these elements using

document.querySelector("textarea.one")
and then update the value:
document.querySelector("textarea.one").style.display = "none";

In order to trigger this JavaScript, you need an event. You can utilize the onClick event. For example,

<img id="header1" onClick="document.querySelector('textarea.one').style.display = 'none';" src="/1.svg" alt="Open Menu" class="menu">

would alter the display property of the textarea.one element upon clicking.

Method I: To target multiple elements, consider adding an additional class to the elements you want to hide, then apply the above code with the updated class. For instance, add class hideOne to textarea one and three and then conceal the elements with

document.querySelector("hideOne").style.display = "none";

Method II: Another approach is to create a function that hides the two components. Create a script tag and use the selectors to hide the elements:

<script>
function hide1(){
document.querySelector('textarea.one').style.display = "none"
document.querySelector('textarea.three').style.display = "none"
}
</script>

Then invoke the function by inserting it into the clickable element (your svg): onClick="hide1()"

That's all there is to it!

Answer №2

Here is a concise method to achieve the same result without relying on jQuery.

While not as straightforward as using jQuery, this approach includes some interesting elements:

  1. I implemented a "delegated event attachment" by attaching the click event handler to the parent element (the first div in the document) of the three <img> elements. This helps maintain document performance and allows for easy extension with additional elements.
  2. To identify the clicked image, I utilize its id attribute: only if the clicked element's tagName==="DIV" and its id starts with "header", will I extract the remaining portion (id-string - 1) to find the corresponding class name c in the cls array.
  3. Within the txtas.forEach() loop, I show the <textarea> containing the class c in its classList, while hiding all others.

const cls=["one","two","three"],
      txtas=document.getElementsByName("myInput");
document.querySelector("div").onclick=ev=>{ let el=ev.target;
  if(el.tagName==="IMG"&&el.id.substr(0,6)==="header"){
    let c=cls[el.id.substr(6)-1];
    txtas.forEach(t=>t.style.display=t.classList.contains(c)?"":"none");
  }
}
<div>
      <img id="header1" src="/1.svg" alt="first" class="menu">
      <img id="header2" src="/2.svg" alt="second" class="menu">
      <img id="header3" src="/3.svg" alt="third" class="menu">
</div>

<div class="textniz">
  <textarea class="one" name="myInput" readonly>
Line one
Line two
Line three</textarea>
</div>

<div class="textniz">
  <textarea class="two" name="myInput" readonly>
Line four
Line five
Line six</textarea>
</div>

<div class="textniz">
  <textarea class="three" name="myInput" readonly>
Line seven
Line eight
Line nine</textarea>
</div>

I have omitted the id attributes from your <textarea> elements to avoid duplicates. The script functions effectively without them.

Answer №3

Not achievable using solely CSS, but can be easily implemented with JQuery (which I believe is more beginner-friendly than pure javascript due to its semantic simplicity).

Here's an example:

$("#header1").click(function(){
  $(".two").hide();
  $(".three").hide();
  $(".one").show();
});
$("#header2").click(function(){
  $(".one").hide();
  $(".three").hide();
  $(".two").show();
});
$("#header3").click(function(){
  $(".one").hide();
  $(".two").hide();
  $(".three").show();  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
      <img id="header1" src="/1.svg" alt="Open Menu" class="menu">
      <img id="header2" src="/2.svg" alt="Open Menu" class="menu">
      <img id="header3" src="/3.svg" alt="Open Menu" class="menu">
</div>

<div class="textniz">
  <textarea class="one" id="myInput" name="myInput" readonly>
Line one
Line two
Line three</textarea>
</div>

<div class="textniz">
  <textarea class="two" id="myInput" name="myInput" readonly>
Line four
Line five
Line six</textarea>
</div>

<div class="textniz">
  <textarea class="three" id="myInput" name="myInput" readonly>
Line seven
Line eight
Line nine</textarea>
</div>

Answer №4

When it comes to quickly switching between views and only needing one view active, jQuery is the way to go. It's a straightforward and easy-to-use solution, as @Alvaro has already demonstrated with a quick code snippet. jQuery allows for easy manipulation and customization.

It's important to note that while jQuery simplifies the process immensely, diving into a full-fledged framework may present more challenges. Starting with jQuery is a great way to get your feet wet and experience its interactive nature.

Keep coding happily :)

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

Automatically advance to the next input field and go back when the backspace key is pressed after reaching the maximum length

Creating a credit card input field that switches cursor after reaching maximum number length and focuses on previous field when deleting with backspace. (function ($) { $(".nmipay-input-field").keyup(function () { if (this.value.l ...

PersistJS callback function is malfunctioning

I stumbled upon a great library for managing client storage. You can find the latest version here: https://github.com/jeremydurham/persist-js However, I encountered an issue with the callback function. var result = store.get('saved_data', func ...

Interactive font-awesome icons within an interactive dropdown menu

I am currently facing an issue with using two Fontawesome icons in a clickable dropdown menu. The dropdown menu does not toggle when I click on the icons directly; however, it works when I click on the padding around them. The example provided by W3schools ...

What is the best way to group all matched objects from an array based on multiple keys?

const data = [ { amount:10, gameId:7 , consoleId:3, id: 1 }, { amount:5, gameId:18 ,consoleId:3, id: 2 }, { amount:5, gameId:18 ,consoleId:3, id: 3 }, { amount:10, gameId:7 ,consoleId:3, id: 4 ...

Creating a unique filter that combines and filters data from two separate API calls for

In my current scenario, I am making two different API calls using Axios in my application. The first call fetches a complete JSON file that populates a table, while the second call retrieves only categories. This setup is due to the complexity of the app, ...

Locate elements based on an array input in Mongoose

Define the Model: UserSchema = new Schema({ email: String, erp_user_id:String, isActive: { type: Boolean, 'default': true }, createdAt: { type: Date, 'default': Date.now } }); module.export ...

How to trigger a function in a separate component (Comp2) from the HTML of Comp1 using Angular 2

--- Component 1--------------- <div> <li><a href="#" (click)="getFactsCount()"> Instance 2 </a></li> However, the getFactsCount() function is located in another component. I am considering utilizing @output/emitter or some o ...

Can you explain the significance of triple brackets (e.g. {{{ content }}}) in the context of Javascript/Typescript?

As I delve into the code of a fresh project in which I hope to contribute, I have come across numerous methods defined with triple brackets, like so: deinitialize() {{{ this.destroyed = true; $(window).off("resize", this.resize as () => void); ...

Ways to prevent styles from being overridden by those specified in JavaScript

Some elements on my page have their style dynamically changed by JavaScript. However, I want one of them to maintain its static style without being overridden. Is there a way to specify that the style of this particular element should not be altered? Than ...

Disabling the Enter key to submit an AJAX form is causing the focus to not move to the next input field

I've encountered a small issue that I can't seem to find a solution for (maybe my keyword search wasn't effective): The scenario: I have successfully prevented a form from being submitted when hitting the Enter key (13). It's importan ...

Pressing the dart key will alter the sprite's direction in a 2D game

Recently, I've been working on a Dart game where the user controls a space ship sprite using the W, A, S, and D keys. Pressing these keys will move the sprite up, left, right, and down respectively. Additionally, pressing the Space bar will launch a p ...

Having trouble with the Express.js app.post request functionality

I'm facing a challenge with the Express.js library. I've been attempting to set up a basic post request with the route. I have body-parser installed and am using it for the post data. If I specifically include app.post, it doesn't work, ...

Display hyperlinks upon hovering over text

In the sign-up form, there are options for two different types of users: teachers and students. When the sign-up option is selected, a drop-down menu with choices for teacher and student will appear. However, I would like it to function more like other w ...

Attempting to reset the altered values proves ineffective in different Ctrl instances within AngularJS

I'm feeling a bit disoriented regarding my current issue. The scenario involves two views and a controller that interact with a service. The first view consists of a table list containing items loaded from a WebAPI. The service sends requests to the s ...

Navigate through the document object model and identify every pair of input boxes sequentially to build a JavaScript object

Incorporating a varied number of input boxes into a view based on selections made in a combo box. For instance, selecting '1' from the combo box results in two input boxes being added to the view. Choosing '2' adds four input boxes. Ea ...

php Use cURL and the DOM to extract content with specified CSS styling

Unclear in the title, I want to copy all content from a specific div on an existing webpage (not owned by me). The code successfully extracts the content. Extractor code: // Get Data $curl_handle=curl_init(); curl_setopt($c ...

Entry Points for Logging In

After stumbling upon this pre-styled Material UI login page example, I decided that it was exactly what I needed. However, I ran into an issue when trying to figure out how to store the username and password values. Whenever I try to use 'State' ...

What is preventing this Javascript from running in Firefox and Chrome?

I recently encountered an issue with some Javascript code that functions correctly in Internet Explorer, but fails to work on Mozilla Firefox or Google Chrome. Any insights as to why this might be the case? function returnData(strCode,strProgramCode,strNa ...

When working with an array of objects in Vue.js, what is the optimal approach: replacing the entire array or modifying individual values?

I am currently utilizing Vue and Vuex to dynamically generate components from an array retrieved from SQLite using the library better-sqlite3. let table=[ { id:1, column_1:'data', column_2:'data', column_3:{'1&apo ...

An issue has arisen while trying to run NPM start on ReactJS

Having trouble starting npm (ReactJS) Whenever I try to run the terminal command npm start An error message is displayed: ERROR in multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server /index.js Module not found: Error: Can& ...