Enhance the textarea using Javascript when clicked

I am experimenting with styling my textarea using a combination of JAVASCRIPT and CSS. The goal is to make it expand in size from 20px height to 120px height when clicked, using

document.getElementById("tweet_area")
. However, I am facing an issue where the textarea expands upon any click on the page, rather than just when clicking the textarea itself. Can someone assist me with this? I am new to JavaScript.

<script language="javascript">

      document.onclick=changeElement;

      function changeElement() {

          var textarea = document.getElementById("tweet_area");

          textarea.style.backgroundColor="#fff";
          textarea.style.width="565px";
          textarea.style.color="#000";
          textarea.style.height="120px";
          textarea.style.paddingLeft="1px";
          textarea.style.paddingTop="1px";
          textarea.style.fontFamily="Tahoma";
          textarea.style.fontSize="10pt";
          textarea.style.border="groove 1px #e5eaf1";
          textarea.style.position="inherit";
          textarea.style.textDecoration="none";  
      }

</script> 


<style type="text/css">
#tweet_area{
    width:565px;
    height:25px;
    overflow:hidden;
    margin:1px auto;
    font-family:Tahoma;
    font-size:10pt;
    font-weight:400px;
    color:#000;
    max-width:565px;
    min-width:565px;
    min-height:25px;
    max-height:120px;
    border:groove 1px #e5eaf1;
    padding-right:10px;
}
</style>

Answer №1

Your click handler is currently applied to the entire document:

document.onclick=changeElement;

This means it will respond to a click anywhere on the page. To make it specific to the textarea, try applying it only to the textarea element:

document.getElementById("tweet_area").onclick=changeElement;

Keep in mind that for document.getElementById() to locate your element, the script must be executed after the element has been parsed. You can either place the script block after the element (typically at the end of the body) or wrap your JS code within a window.onload handler.

Additionally, as a recommendation, instead of setting individual styles in your JS function, consider creating a CSS class with those styles and then simply adding the class using your JS code.

Answer №2

Utilize CSS to customize your textarea, eliminating the need for javascript styling in this case. Create your style in CSS within a specific class and simply add this class and its properties when necessary. This approach offers a more organized solution. Use focus and blur events to access the textarea element. Check out this example.

HTML

<textarea rows="4" cols="50" id="txtArea">

<textarea>

JS

$(document).ready(function() {

    $('#txtArea').on("focus", function(event) {

        if(!$('#txtArea').hasClass('customTextAreaClass')){

            $('#txtArea').addClass('customTextAreaClass');

        }
    });

    $('#txtArea').on("blur", function(event) {

        if($('#txtArea').hasClass('customTextAreaClass')){

            $('#txtArea').removeClass('customTextAreaClass');

        }
    });
});

CSS

.customTextAreaClass{
    background-color: #fff;
    width: 565px;
    color: #000;
    height: 120px;
    padding-left: 1px;
    padding-top: 1px;
    font-family: "Tahoma", Geneva, sans-serif;
    font-size: 10pt;
    border: groove 1px #e5eaf1;
    position: inherit;
    text-decoration: none;  
}

Answer №3

I recently created a jQuery script to resize a Textarea when the user hits the Enter Key within the designated field. Alternatively, you could modify the script to work with a Click Event for the Textarea.

You can find the code snippet here: https://example.com/post123456

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

Error: Unexpected TypeError occurred stating that 'map' cannot be read from undefined, although the map method is not being used in the code

I have recently developed an Ethereum application for conducting transactions using React and the ethers module. Below, you can see a snippet of my code, specifically focusing on the function sendTransactions: import {ethers} from 'ethers'; impor ...

Refresh text displayed on a button with the help of setInterval

I need help updating the text on a button with the id fixed-button at regular intervals. Here is the code I am currently using: <script type="text/javascript"> $(function() { $('#fixed-button').setInterval(function() { ...

Retrieve information from the index resource using AJAX

I feel like I might be overcomplicating things, but basically, I'm trying to retrieve all the data from an index resource and have it load when a button is clicked using AJAX. I've been using a serializer to tidy up the JSON. Both "/categories" ...

What is the importance of using ChangeDetectorRef.detectChanges() in Angular when integrating with Stripe?

Currently learning about integrating stripe elements with Angular and I'm intrigued by the use of the onChange method that calls detectChanges() at the end. The onChange function acts as an event listener for the stripe card, checking for errors upon ...

The selection discrepancy is due to the misalignment between the cursor and white space in the CSS styling

Upon close inspection, I've discovered that a discrepancy exists between the selection on my webpage and the cursor position. After investigating further, I uncovered the following reasons: Presence of white-space between the start tag <p> and ...

How can you attach a d3 graphic to a table that was created automatically?

Calling all experts in d3, I require urgent assistance!! On this web page, a JSON is fetched from the server containing 50 different arrays of numbers and related data such as 90th percentiles, averages, etc. A table is dynamically created with the basic ...

Node.js/Firebase function to delete an item from a JSON object and update the existing items

I'm currently facing a challenge with updating a JSON file in Firebase after deleting an item using the .delete() function. Here is the original JSON data before deletion: "data": [ { "position": "3", ...

Enhancing Your Images with jQuery

Hello When working with jQuery, the following code can be used to darken an image. On the contrary, how would you go about brightening up an image? $(this).hover(function() { $(this).stop().animate({ opacity: 0.5 }, 500); }, function() { $(thi ...

absence of an export called

I am facing an issue with importing a simple component in my React project. I am unable to locate the component causing this error. The error message I am receiving while importing the component is as follows: ./src/App.js 61:28-32 './componentes/ ...

Tips for reducing text in a card design

As a newcomer to codeigniter 4, I recently created an event card with a lengthy description. However, when I attempted to display the event data from the database on the card, it ended up becoming elongated due to the length of the description: https://i. ...

What is the best way to align my content alongside my sidebar?

I am facing some challenges with my website layout because I used Bootstrap to integrate a sidebar. The sidebar has caused issues with the positioning of my content, and I'm struggling to align it properly next to the sidebar on the left side. Please ...

What could be causing the Material UI tabs to malfunction when dynamically populating the content using a .map function instead of manually inserting it?

I was able to successfully integrate Material UI's tabs by manually adding content, but when I attempted to use a .map function to populate the content from a JSON data source, it stopped working. Can someone help me figure out why? The only change I ...

What is the process for linking to a backend on a distinct port in Next.js?

I am working on a project with Next.js and I am facing a challenge in connecting to a backend server that is running on a different port. The frontend of my application is on port 3000, while the backend is on port 8000. My goal is to interact with the bac ...

Tips for keeping the menu open even when you're not hovering over it with your cursor

I put together a stylish drop-down menu based on some web examples, but my manager pointed out that it can be inconvenient to use because the menu closes when the mouse moves off of it. I've tried various workarounds as outlined here, but none have in ...

JavaScript promises do not guarantee the execution of the loop

There was a block of Javascript code that I needed to modify. Initially, the code looked like this: if(!this.top3){ const promises = this.images.map((el, index) => { return this.getData(el.title, index); }); return Promise.all(promise ...

Transitioning from traditional Three.js written in vanilla JavaScript to React Three Fiber involves a shift in

I am currently faced with the task of converting a vanilla JS Three.js script to React Three Fiber. import * as THREE from 'three'; let scene, camera, renderer; //Canvas const canvas = document.querySelector('canvas') //Number of lin ...

JavaScript: Selecting parent elements using getElementsByClassName

I am dealing with the following HTML code: <div class="item"> <img class="item-image" src="${item.getImage()}"/> <p>${item.getName()}</p> </div> and JavaScript: var classname = document.getElementsByClassName("item" ...

Display Button and Div when Event occurs in Asp.net core using Razor Pages

I am currently working on a project that involves two dropdown menus: one for Categories and the other for SubCategories. Within a partial view named _CreateProject, I have set up an html form to facilitate the creation of new projects. My goal is to have ...

Tips for customizing fonts in a WordPress object

WordPress is sending me an object that I need to work with. The main issue at hand: the font styles of WordPress posts in my app are all inconsistent. How can I go about styling these fonts uniformly? Take a look at this Plunkr if you'd like to expe ...

The JQuery Ajax call returned with a status of 0 and an empty ResponseText

Here is the ajax request I am using: $.ajax({ type: "POST", url: "https://forlineplus.forsa.com.co/projects/validar-redireccion-sio?fup=" + idFup, //contentType: "application/json; charset=utf-8", ...