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

Tips for successfully utilizing hyphens when passing an object property as an argument

Does anyone know how to pass an object property with a hyphen in it as an argument? I'm having trouble with this issue. Object { "section-id": 1, ... } HTML <div *ngFor="let section of sections" (trackScrollLeave)="leave(section.sectio ...

Maintaining Styles After Focus is Removed in CSS: A Guide

The CSS that styles our buttons is as follows: .btn-outline-primary { color: blue; border: 1px solid blue; background: transparent; transition: all 0.3s ease 0s; } .btn-outline-primary:hover, .btn-outline-primary:focus { background: ...

I'm struggling to incorporate the JQuery slideDown function into my code. Can someone lend a hand?

Why isn't the video div sliding down and displaying properly in the beginning? Any ideas on how to fix it? Here is the snippet of HTML code and JavaScript: <!DOCTYPE HTML> <html> <head> <title>Team Songs</title> <link ...

What are the steps to verify if an iframe is lacking content?

I have two different codes: one is null and the other is not null. Code with null value (== empty): <div class="col-xs-6"> <iframe style="width:868px; height:550px;" id="FileReload" src="/Account/GetPDF?NUM=101"> <html> ...

Error: Unable to assign value to property 'src' because it is null

Currently, I am attempting to display a .docx file preview using react-file-viewer <FileViewer fileType={'docx'} filePath={this.state.file} //the path of the url data is stored in this.state.file id="output-frame-id" ...

Issue with Moment.js incorrectly formatting date fields to a day prior to the expected date

Currently, I am attempting to resolve a small issue in my code related to a tiny bug. In my React component, I have set an initial state as follows: const initialFormData = Object.freeze({ date: Moment(new Date()).format('YYYY-MM-DD'), pr ...

Enclose every line of the paragraph within a <span> element

My <div> element is configured to display a paragraph without any line breaks, similar to the example below: <div> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dum ...

Tips for overlapping children in a column flex direction while maintaining the parents' positioning

Currently, I am working with two parent flex items, arranged with flex-direction: column. Within the first parent, there are two children. However, one of the children is optional and may be removed at times. I aim to have the optional child displayed on ...

The issue with MUI TextField: the outline is overlapping the label

Recently, I encountered an issue with a MUI TextField in my project. In its default state, everything appeared fine: https://i.stack.imgur.com/WFzOr.png However, when I increased the font size as per the theme provided below, the label started to overlap ...

Axios removes the async functionality

Is there a way to achieve the same functionality without using the async function? async EnvioLogin() { const response = await axios.post("api/auth/login", { email: this.email, password: this.password, }); localStorage.setItem(" ...

Using a div in React to create a vertical gap between two React elements

I am working with two React Components in my project - the Right Column and the Left Column. I am trying to create space between them using a div tag. Currently, my setup in the App.js file looks like this: import React from 'react'; import LeftC ...

What is the best way to implement a conditional check before a directive is executed in Angular, aside from using ng-if

I am facing an issue where the directive is being executed before the ng-if directive. Is there a way to ensure that the ng-if directive is executed before the custom directive? Could I be making a mistake somewhere? Should I consider using a different ...

Setting the height of a div using CSS and navigating between views using Angular UI

Issue One: When moving one square, the border should appear and the menu should cover the entire height. I've already spent 2 hours trying to fix this, but it still doesn't fill the whole height or center vertically. Problem Two: If you make the ...

Having difficulty creating a shadow beneath a canvas displaying Vega charts

I'm looking to create a floating effect for my chart by adding shadows to the canvas element that holds it. Despite trying various methods, I can't seem to get the shadow effect to work. Here is the code snippet I have for adding shadows: <sc ...

Determine the placement of the body with CSS styling

Here is the code snippet from my website: body { background-image: url('background.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-size: cover; } .centered { /* Center entire body */ display: flex; ...

How to Align React Material UI Grid with Varying Row Counts in Each Column

Objective My goal is to design a component that showcases details about a device, including an icon and its current status. For instance: Approach I've Taken I am attempting to accomplish this by structuring a MUI Grid in the form of a 2x2 grid la ...

Using Material-UI to add a pseudo class '::before' with component class properties

I attempted to utilize a pseudo class for the mui-app-bar but did not have success. I've researched this issue on various platforms without finding a solution. Below is how my component is currently structured: const styles = (theme: Theme) => cre ...

Running a React application through a personalized Express server, all the while ensuring seamless automatic updates throughout the development

I currently have a React application along with a completely distinct Express server application. To serve my React app using a customized express server, I utilize the following code within my Express app: app.get("*", (req, res) => { res. ...

The output of jQuery('body').text() varies depending on the browser being used

Here is the setup of my HTML code: <html> <head> <title>Test</title> <script type="text/javascript" src="jQuery.js"></script> <script type="text/javascript"> function initialize() { var ...

Steps for moving data from a JavaScript variable to a Python file within a Django project

I have created a unique recipe generator website that displays each ingredient as an image within a div. When the div is clicked, it changes color. My goal is to compile the ids of all selected divs into one array when the submit button is clicked. I have ...