Adjust the text color of a div element by clicking a button with the help of JavaScript

I am trying to change the font color of my div when a button is clicked using JavaScript. The two buttons I have are 'Green' and 'Red'.

<button type="button" class="green">Green</button>
<button type="button" class="red">Red</button>

Here is my div:

<div id="timer"></div>

Currently, the font color is red (default color). When 'Green' is clicked, it should turn green, and when 'Red' is clicked, it should go back to red.

It seems like a simple task, but for some reason, I can't seem to get it to work :)

If you have any insights on how to achieve this, I would greatly appreciate it.

Answer №1

To easily change the color without using JQuery, you can simply add an onclick event to a button like this: http://jsfiddle.net/8jay6r3n/

Just include the following code in your HTML:

onclick="document.getElementById('timer').style.color = 'red'"

For more information on how this works, check out the documentation here: http://www.w3schools.com/js/js_htmldom_css.asp


If you prefer to use jQuery, you can view an example here: http://jsfiddle.net/8jay6r3n/2/ You have the option to use inline styles or add a class to change the text color.

Answer №2

For those just starting out, using the jQuery library can make things much simpler.

To get started, all you need to do is insert the following code in the <head> section of your document to install jQuery and enable the $ function:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

After that, your solution could look something like this:

$('#green').click( function() { $('#timer').css('color','green'); } );
$('#red').click( function() { $('#timer').css('color','red'); } );

Answer №3

Here is an example showcasing the use of links:

Check out the Javascript code below:

<script language="javascript">
function changeBackgroundColor(color) {
  document.getElementById('clock').style.backgroundColor = color;
}
</script>

Below are the links that you can click on to change the background color:

<a href="javascript:changeBackgroundColor('#000000');">Black</a> 
<a href="javascript:changeBackgroundColor('#FF0000');">Red</a>

This is the div element that will have its background color changed by clicking the links above:

<div id="clock" style="font-weight:bold; font-size:10px">Clock</div>

It should work similarly for buttons as well.

Answer №4

Give this a shot with some jQuery magic

$('.blue').click( function() { $('#clock').css('color','blue'); } );
$('.yellow').click( function() { $('#clock').css('color','yellow'); } );

http://jsfiddle.net/5abjk/23/

Answer №5

If you prefer utilizing jquery, the implementation process becomes much simpler. You can include the function in a JavaScript file or within a <script> tag.

   $('#timer').css('color','green'); 
});
$('#red').click( function() {
   $('#timer').css('color','red'); 
});

Alternatively, if you opt for using pure javascript, you can utilize either "addEventListener" or 'click' for handling click events and then specify styling for each tag/element where you wish to apply css.

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

The Ajax post function successfully executes on the first attempt, but on subsequent tries it does

My goal is to send data from a forum asynchronously to a PHP page and display the response in a specific ID without refreshing the page. The first time I submit, everything works perfectly. The text is successfully sent to append.php and the new list of i ...

Resetting values in Javascript and JQuery when clicking a button

I've recently implemented a feature on my website header where clicking on the search button reveals a search bar, and clicking on the account button reveals an account bar. With some valuable assistance from Madalin, I was able to achieve this functi ...

What is preventing me from retrieving an ID value within an IF condition?

I'm trying to create a script that only allows devices with matching IP addresses, but I'm having trouble using an if statement. Whenever I include x.id inside the statement, it doesn't seem to work... any suggestions? <html> <sc ...

Encountering issues with the functionality of async await

I am a beginner when it comes to utilizing the async, await, and promise features in JavaScript. My current focus is on: async function sendTextMessage(text) { console.log("----1----"); var messageData = { message: { text: tex ...

Steps to trigger an alert when the entered quantity exceeds the current stock levels

After developing an IMS System, I encountered a problem where my stock is going into negative figures. To resolve this issue, my primary goal is to trigger an alert whenever the quantity entered by a user exceeds the available stock. For example, if a us ...

What is the correct way to integrate a new component into my JHipster + Angular project while ensuring that the routerlink functions properly?

After creating a new application on JHipster, I wanted to add a FAQ page to my web portal. However, the default CRUD components generated by JHipster made it look more like an admin/user view table. I needed to make the FAQ page accessible to visitors with ...

The attempt to connect with react-native-fetch-blob has not been successful

How do I resolve the issue of displaying a PDF from my assets folder in an Expo, React Native project using react-native-pdf? While scanning folders for symlinks, encountered an error with RNFetchBlob library in my project directory. The automatic linki ...

In CodeIgniter, the $this->input->post() function consistently returns an empty value

I'm encountering an issue where the value from an AJAX post always turns out empty. Even after confirming that the value is correct before the post, I'm unable to retrieve it using $this->input->post() HTML <?php if ($product_info-> ...

Filtering objects by their properties or attributes in AngularJS can be achieved by using forEach, but encountering an error stating "forEach is

In my AngularJS application, I have a page that displays multiple widgets. One widget shows a table with details about a monitored system. Currently, the table has two columns: 'Type' and 'Data', displaying information and values respec ...

Selecting and Uploading Multiple Files in Internet Explorer (less than version 9)

I have been struggling with selecting and uploading multiple files at once to the server. Here is the code I am currently using: <html> <body> <form action="upload.php" method="post" enctype="multipart/form-data" name="myForm"> <l ...

Creating a new dynamic page can be achieved by clicking on a dynamically generated link. Would you like to learn how to do that?

Recently, I developed a custom API using Node.js to retrieve information about blogs from Medium.com. The API currently provides: The author/main picture of the article Title A link to the article on medium.com (redundant) The entire article text in the ...

Tips for hovering over a link with Webdriver

Currently, for my project, I am utilizing Selenium Webdriver. Successfully automating the functionality to mouse over an image has been achieved. However, there seems to be an issue when attempting to trigger a mouse-over event on a hyperlink using the sam ...

Include the circle.css file in the Angular 4 project by loading it in the head section of the

I am currently working with Angular 4 and would like to incorporate the circle.css styles from cssscript. After downloading the file from the provided link, I placed the circle.css within my something component file. However, when attempting to use &l ...

The autocomplete feature in Codemirror seems to be failing specifically when writing JavaScript code

I am having trouble implementing the autocomplete feature in my JavaScript code editor using Codemirror. Can someone please help me figure out what I'm doing wrong? Here is the snippet of code : var editor = CodeMirror.fromTextArea(myTextarea, { ...

No feedback received after sending keys using Selenium

Whenever I execute my code using PhantomJS and Selenium, the result appears to be correct. However, when it comes to using send_keys function, the code gets stuck without any errors, answers, or progress. I am puzzled and eager to find out why this is ha ...

Encountering a situation where attempting to retrieve JSON data results in receiving an undefined

After fetching JSON data from the API , I successfully printed out text to the console with the correct data. However, when attempting to access any of its properties, they are returning as undefined. var url = "http://www.omdbapi.com/?t=batman&y=& ...

Opt for Observable over Promise in your applications

I have implemented this function in one of my servlets: private setValues() { this.config.socket.on('config.weather', (values:any) => { console.log(values); } However, I would like to refactor it to something like this: private se ...

How can I retrieve console log information in POSTMAN when a test fails?

Having an issue with this test. I am trying to trigger a console.log when the installment value in my JSON is less than 100 (resulting in a test FAIL). However, I am receiving both PASS and FAIL results in the test, but no information is showing up in th ...

Is it possible to restructure the address 51.xx.xx.xx:33xxx:user:pass to display as user:[email protected] :33xxx instead?

I am facing an issue with my current code where it only returns one proxy because it keeps rewriting over the existing ones. I want to avoid creating a new file and instead update the 'proxies.txt' file with each new proxy. const fs = require("f ...

Unable to connect to server using React-Native fetch. Localhost is not being used

I recently encountered an issue with my app where the fetch function used for user authentication stopped working. Despite not making any changes, the transition from React 0.27 to 0.28 seemed to have caused this problem. After scouring through numerous S ...