Tips for adjusting the appearance of text dynamically using JavaScript and CSS when a button is clicked

I'm trying to change the color of the text after a button click. Currently, the text color is blue before clicking the button, but I want it to be green after the click. I've searched online for solutions, but I haven't been successful. Here's my code:

button {
border: 1px solid black;
color: white;
background-color: black;
padding: 10px 20px;
font-size: 15px;
cursor: pointer;
transition-duration: .5s;
}
button:hover {
background-color: blue;
}
p {
color: blue;
font-size: 20px;
}
<p id="demo">Hello everyone! I will get changed after being clicked :)</p>

<button onClick='document.getElementById("demo").innerHTML = "I appear after clicking the button :P"' class="xx">Click</button>

I'm new to JavaScript, so I'm struggling to achieve the desired result. I've tried adding (id="xx") after .innerHTML inside the <button> tag and styling it with CSS, but it didn't work as expected:

<!DOCTYPE html>
<html>
<head>
<style>
button {
border: 1px solid black;
color: white;
background-color: black;
padding: 10px 20px;
font-size: 15px;
cursor: pointer;
transition-duration: .5s;
}
button:hover {
background-color: blue;
}
#xx {
font-size: 20px;
color: blue;
}

</style>
</head>
<body>


<p id="demo">Hello everyone! I will get changed after being clicked :)</p>

<button onClick='document.getElementById("demo").innerHTML(id="xx") = "I appear after clicking the button :P"' class="xx">Click</button>



</body>
</html>

I've tried various unsuccessful attempts, and I'm stuck. Can someone guide me on how to change the text style after clicking the button?

Here's an example of the desired output:

https://i.sstatic.net/5NwIA.jpg

Answer №1

Here is one method to achieve this:

const button = document.querySelector('#btn');
button.addEventListener('click', changeText);
function changeText() {
 let paragraph = document.querySelector('#demo');
 paragraph.innerHTML = "I will change after the button is clicked!"; 
 paragraph.classList.add("new-style");
 }
button {
border: 1px solid black;
color: white;
background-color: black;
padding: 10px 20px;
font-size: 15px;
cursor: pointer;
transition-duration: .5s;
}
button:hover {
background-color: blue;
}
p {
color: blue;
font-size: 20px;
}
.new-style {
  color: green;
}
<p id="demo">Hello, everyone! I will change when you click me!</p>
<button id="btn" class="xx">Click Me</button>

Answer №2

Review this snippet.

<!DOCTYPE html>
<html lang="en>
<head>
    <meta charset="UTF-8>
    <title>Sample with button</title>
    <style>
        body {
            color: blue;
        }
        button {
            border: 1px solid gray;
            color: white;
            background-color: gray;
            width: 150px;
            height: 40px;
            font-size: 15px;
            cursor: pointer;
        }
        button:hover {
            border-color: darkolivegreen;
            background-color: darkolivegreen;
        }
        .newstyle {
            color: green;
        }
    </style>
    <script>
        function change_text_color() {
            let text = document.querySelector('#demo')
            text.innerHTML= "I changed color after button click :P";
            text.className = "newstyle";
        }
    </script>
</head>
<body>
    <p id="demo">Hello everyone! I will get updated after click :)</p>
    <br/>
    <button onClick='javascript:change_text_color();' class="xx">Press here</button>
</body>
</html>

Answer №3

Understanding element precedence in CSS can be tricky, but one simple approach is to assign a class to your demo element to define its initial color, and then use a button to apply a new color class.

const demo = document.querySelector('#demo');
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false);

function handleClick() {
  demo.textContent = 'I appear after clicking the button';
  demo.classList.add('green');
}
.blue { color: blue; }
.green { color: green; }
<p id="demo" class="blue">Hello everyone! I will get changed after being clicked :)</p>
<button>Click</button>

Answer №4

In this scenario, you have two main choices. The first option is to include the <font> tag within your innerHTML.

<button onClick='document.getElementById("demo").innerHTML = "<font color='#90ee90'>I appear after clicking the button :P</font>"' class="xx">Click</button>

Alternatively, you can utilize JavaScript to alter the color.

document.getElementById("demo").style.color = 'green';

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

Ways to modify the header color of a card by utilizing a Select element in Javascript, while ensuring that it does not impact other cards

I am facing an issue with multiple cards, each containing a Select element. When a user selects an option from the Select element, the card header changes color, but it also affects all other card headers. How can I separate them? [data-background-co ...

What is the process for executing Selenium IDE scripts in Selenium RC?

As a newcomer to using the selenium testing tool, I am seeking guidance on running selenium IDE scripts within selenium RC. I would greatly appreciate examples and screenshots to help me better understand the process. ...

What is the best method to prevent next.js components from overlapping one another?

I recently created a website using next.js and noticed an issue in my index.js file. There is a div that houses the main components of the site: class Page extends Component { render() { return ( <div className={styles.container}> ...

Guide to summing the values in an input box with TypeScript

https://i.stack.imgur.com/ezzVQ.png I am trying to calculate the total value of apple, orange, and mango and display it. Below is the code I have attempted: <div class="row col-12 " ngModelGroup="cntMap"> <div class="form-group col-6"> ...

Stop the default drag behavior on an input range element in VueJS

Is there a way to disable the default drag functionality of an input range element without affecting the click feature? Users should be able to change values by clicking instead of dragging. <input type="range" min="0" max=& ...

iPhone 6 (iOS) users may face compatibility issues with iframe and fancy box features

I am currently learning how to use jQuery and the fancybox library. In my Angular 1 and Ionic project, I have successfully implemented fancybox with an iframe. Everything works perfectly on browsers and Android devices, but on iOS, a loader icon appears an ...

Oops! The function 'ModalDemoCtrl' has not been defined, causing an error

Hey there, I'm encountering an error when using angularJS in my project. The project is built on the django framework and does not include any additional JS files. Here are some snippets of my code: JavaScript: {{ ngapp }}.controller("ModalDemoCtrl" ...

What is the simplest method for fetching and parsing JSON data with jQuery and JavaScript?

I'm having trouble making this code snippet work. I can't seem to figure it out. The objective is to retrieve and parse a JSON object in the simplest and easiest way possible. Here's the code snippet. <!DOCTYPE html> <html> &l ...

Center the HTML elements on the page

After struggling for some time, I can't seem to figure out how to center elements in the middle of a page without having a lengthy navigation bar at the bottom of the screen. Does anyone have any suggestions? https://codepen.io/picklemyrickle/pen/XWj ...

Tips on positioning content beneath a fixed header or navigation bar when viewed in a web browser

Hi, I'm having an issue with creating a fixed header using HTML and CSS. When I set my header to be in a fixed position, it covers up the content below it. I want the content to be positioned under the header when the page is loaded. Additionally, I&a ...

Exiting the window event

While searching the internet for a solution, I discovered that the method I thought was the simplest way to handle a window being exited (window.unload()) has been deprecated in an earlier version of jQuery. Does anyone know of a straightforward approach t ...

The value returned by a component should remain consistent regardless of where it is invoked. Additionally, the main component in React should not re-render when the state of a sub-component is

I am looking to have the same value displayed in the Home function from the Component, without causing a rerender when the useState in Component is updated. import { useState, useEffect } from "react"; function Component() { const [count, setC ...

Is it possible to invoke a helper function by passing a string as its name in JavaScript?

I'm encountering a certain issue. Here is what I am attempting: Is it possible to accomplish this: var action = 'toUpperCase()'; 'abcd'.action; //output ===> ABCD The user can input either uppercase or lowercase function ...

The HTMLElement type does not include the Ionic typescript property

I am currently using Ionic v3 with TypeScript. My goal is to store the file_url in an array after checking if its width is equal to twice its height. However, I am encountering an error: The 'name_array' property does not exist on the ' ...

Specialized Node.js extension for automatic dependency installation

My current setup involves a custom Yeoman generator for specific applications, which comes with its own set of dependencies and configurations. - GruntJS must be installed globally; - Bower must be installed globally; - Yeoman must be installed globally ...

How can one elevate the properties of each item's sub-structure to the root level in an array containing object items?

I am working with an array containing objects, each with a specific structure... [{ user: { /* ... more (nested) user data ... */ }, vacation: { id: 'idValue', name: 'nameValue', startDate: 'dateValue', }, }, ...

Enhance your Django webpage with real-time updates using AJAX technology

[Revised for Clarity and Detail] The challenge I'm facing is related to the architecture of my project. I have multiple ideas on how to achieve my goal, but I'm stuck on identifying the correct or most efficient approach. To provide more context ...

The box shadow feature does not function properly when the position is set to sticky

Applying position sticky to th and td in the example below seems to be causing issues with the box shadow not working. Can anyone provide insights on why this is happening? <div class="overflow-x-auto lg:overflow-visible"> <div> <t ...

GWT integration for TinyMCE

I've been attempting to incorporate TinyMCE with GWT's RichTextBox, but so far I haven't had any luck. The issue seems to be that GWT turns the Rich text area into a #document, rather than a standard textarea in HTML. Does anyone know how to ...

*Arabic text styled in italics using JavaFX*

I'm having an issue trying to italicize Arabic text, It just won't work, I've experimented with different fonts as well, but none seem to be working, Here's the code snippet: import javafx.application.Application; import javafx.scene.S ...