click button to display text javascript

Click Button to Display Text Javascript

Displaying text on a webpage dynamically is a common requirement. One of the easiest ways to do this is by using JavaScript to display text when a button is clicked. Here's how you can do it:

Method 1: Using InnerHTML property

First, create a div element with an id that you'll use to display the text:

<div id="text"></div>

Then, create a button element with an onclick event handler that will call a JavaScript function:

<button onclick="displayText()">Click me</button>

Finally, create the JavaScript function that will change the innerHTML property of the div element to display the desired text:

function displayText() {
  document.getElementById("text").innerHTML = "Hello, world!";
}

Now, when the button is clicked, the "Hello, world!" text will be displayed in the div element.

Method 2: Using AppendChild method

If you want to add new text every time the button is clicked instead of replacing the existing text, you can use the appendChild method instead of the innerHTML property:

<div id="text"></div>
<button onclick="displayText()">Click me</button>
function displayText() {
  var para = document.createElement("p");
  var node = document.createTextNode("Hello, world!");
  para.appendChild(node);
  var element = document.getElementById("text");
  element.appendChild(para);
}

This will add a new paragraph element with the "Hello, world!" text every time the button is clicked.

Method 3: Using Jquery

If you're using jQuery, you can simplify the code even further:

<div id="text"></div>
<button id="btn">Click me</button>
$(document).ready(function() {
  $("#btn").click(function() {
    $("#text").text("Hello, world!");
  });
});

This will achieve the same result as the first method, but with less code.

There are many other ways to display text when a button is clicked, but these methods should cover most basic requirements. Experiment with different approaches to find the one that works best for your specific use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe