JavaScript code for modifying style properties

Is there a way to modify this function so that when the heading is changed successfully, a "Change Back!" button appears? And then, with a click on the button, the heading is reset and the button disappears again.

function changer () {

  var textArea = document.getElementById("text_box").value;

  if (textArea.length === 0) {
     alert("Please enter a value.");
     return;
  }
  var heading = document.getElementById("heading");
  heading.innerHTML = textArea;
}
#change_back {
  display: none;
}
<!-- HTML -->
<h1 id="heading">This is a heading</h1>
<button id="change_back">Change Back!</button>

<input type="text" id="text_box">
<input type="submit" onclick="changer()">

Answer №1

To toggle the visibility of an element, we can define a CSS class for the "hidden" state and dynamically apply or remove it as necessary.

const btnReset = document.getElementById("change_back");
const defaultText = 'This is a heading';

const show = (elem) => {
  elem.classList.remove("hidden");
}

const hide = (elem) => {
  elem.classList.add("hidden");
}

function changer() {

  var textArea = document.getElementById("text_box").value;

  if (textArea.length === 0) {
    alert("Please enter a value.");
    return;
  }
  var heading = document.getElementById("heading");
  heading.innerHTML = textArea;
  show(btnReset);
}

const reset = () => {
  document.getElementById("heading").innerHTML = defaultText;
  hide(btnReset);
}
.hidden {
  display: none;
}
<!-- HTML -->
<h1 id="heading">This is a heading</h1>
<button id="change_back" class="hidden" onclick="reset()">Change Back!</button>

<input type="text" id="text_box">
<input  id="btn_submit" type="submit" onclick="changer()">

Answer №2

Feel free to test out the example code provided below that will reset the heading value.

const defaultText = 'This is a heading';

function resetText () {
  document.getElementById("change_back").style.display = 'none';
  var heading = document.getElementById("heading");
  heading.innerHTML = defaultText;
}

function changer () {
  document.getElementById("change_back").style.display = 'block';
  var textArea = document.getElementById("text_box").value;

  if (textArea.length === 0) {
     alert("Please enter a value.");
     return;
  }
  var heading = document.getElementById("heading");
  heading.innerHTML = textArea;
}
#change_back {
  display: none;
}
<!-- HTML -->
<h1 id="heading">This is a heading</h1>
<button onClick="resetText()"  id="change_back">Change Back!</button>

<input type="text" id="text_box">
<input type="submit" onclick="changer()">

Answer №3

Start the application by initializing a global variable called prevHeadingTxt as null. Upon calling the changer() function, this variable will hold the previous content of the heading.

This mechanism allows for dynamic updates to the heading, keeping track of both the current and previous values. The value can also be reset using the prevHeadingTxt variable.

let prevHeadingTxt;  // Initialize the heading. 

function changer () {
    prevHeadingTxt = document.getElementById("heading").innerHTML;  // Store the previous heading
    let textArea = document.getElementById("text_box").value;

    if (textArea.length === 0) {
       alert("Please enter a value.");
       return;
    }

    let heading = document.getElementById("heading");
    heading.innerHTML = textArea; 
    document.getElementById("change_back").style.display = 'block';  // Make the button visible
}

function resetHeading(){
    let heading = document.getElementById("heading").innerHTML = prevHeadingTxt;
    document.getElementById("change_back").style.display = 'none';   // Hide the button after reset 
}

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

How wide should the website layout be?

What is the perfect size for a standard portal website? I've seen many sites with widths ranging from 960px to 1000px. ...

What is the best method for accessing a specific Data value on the route?

Hello everyone! This is my first time posting on Stack Overflow. I am currently working on developing an attendance management system for a school. In my database tables, I have the following fields: Registration: class_id, section_id, user_id. Attendanc ...

Managing the invocation of a promise multiple times in AngularJS, and handling some specific exceptions

After previously asking a question on handling promises multiple times in AngularJS (AngularJS handle calling promise multiple times), I am facing a new challenge. This time, I need to retrieve a list of cities, but encounter an exception. Similar to how ...

Ways of extracting specific information from a JSON file with the help of jQuery

I am currently attempting to parse a JSON file that is stored locally on my system using jQuery. I am specifically interested in retrieving certain data from the file, which is structured like this: {"statements":[{"subject":{"uriString":"A","localNameIdx ...

Is it possible to retrieve 2 arguments within a function in a non-sequential manner?

Let's say there is a function with arguments A, B, C, D, and E. Function(A, B, C, D, E) However, not all arguments are needed all the time. For instance, only A and C are needed in some cases. Currently, I would have to call the function like this: Fu ...

Concealing unnecessary borders on list elements using jQuery

Here is the code I am working with: http://jsfiddle.net/eLyJA/ I am looking to calculate and eliminate all border edges to achieve this visual effect: ...

Can anyone provide guidance on how to trigger 3 unique functions in a specific order using JavaScript?

I've been troubleshooting this issue for quite some time, but I just can't seem to figure it out. Here's my dilemma: I have three functions - one to shrink a div, one to reload the div with new data, and one to enlarge the div - all triggere ...

Background PHP/JS authentication through HTTP

Recently, I developed a PHP website that includes embedded web-cam snapshots which refresh every 2 seconds using JavaScript. For the first camera, I can easily log in using URL parameters like this: cam1-url?usr=usr&pwd=pwd. However, the second camer ...

Guide to retrieving and editing images from Appwrite using Vue

Currently, I am utilizing a View frontend to retrieve a PDF file from Appwrite Storage. My goal is to acquire the PDF, insert additional text onto it, and then save it to the user's local device. Below is the code I have so far - although I can recei ...

Translating Bootstrap 5 into Angular components for version 13 and above

In Angular, the lack of support for optional host-elements and containerless components means that each component comes with its own div wrapper. However, when designing Bootstrap components, a host-less component (without an extra div) is needed to mainta ...

Struggle with the background div menu

I am trying to create a menu with a background color, but when I use "background" or "background-color" on the div that contains my menu, I can't see any color. It's frustrating because I know it should be working.. Here is the HTML : <head ...

Problem with Jquery Ajax, failing to recognize option values

Hello everyone, please review the code snippet below... $.fn.myajax = function (options) { var defaults = { my_event: "", my_url: "", my_data: "", } var o = {}; var mydata = options.my_data; $.extend(o, default ...

Guide to finding your way to a specific section in React

I attempted to navigate to a particular section within a page. I also tried to include an id in the component, but it didn't function as expected <Login id ="login_section > ...

Having difficulty incorporating custom JavaScript files into a testing framework

I am facing a unique challenge while integrating the Page Object design pattern into my test suite using selenium-webdriver and node.js. The first page object, pageObject/admin/login/index.js, works seamlessly. It contains selectors and methods to fill ou ...

Transferring application configurations across modules

Questioning my current approach, I am developing a model & collection package (which exposes mongodb results as a model) and aiming for a modular structure. However, within the models, there are hardcoded settings like host, port, password, etc., which ...

Checking for the existence of a value in an object using Angular loops

I am seeking assistance in verifying the presence of a specific value within an object. My Object = (vagas.etapas) "Etapas" : { "05daf060-87cb-47cf-8c98-65b36941613d" : "Name 1", "0bf7aabf-42df-4f7d-86dc-af81e6cef394 ...

Explore the flexibility of npm by installing and utilizing various versions of a specific package

Is it possible to install and utilize different versions of packages in npm? Installation can be done as follows: npm install -g <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d6d7c7e767c7a78737c70785d2f3325">[email p ...

The React data editor Dialog closes when the drop-down is clicked without triggering any onChange events

Utilizing the react-datasheet component, I have implemented a table to display a matrix/grid of data. To enhance user experience, I customized the dataEditor to launch a custom dialog where users can only choose from preselected values in a material-ui dro ...

Finding the index and value of a specific HTML element with jQuery click event

I'm currently working on creating an Ajax function to delete items from a list using Jquery ajax. Here is the HTML structure: <ul> <li><a class="del"><span style="display:none;">1</span></a></li> <li& ...

How come the error message in AngularJS is appearing as blank during error handling?

When utilizing AngularJS code to send a request to the server, everything works smoothly on success. However, deliberately redirecting the request to a different domain causes the CORS problem where the error handling function is triggered but errorData ...