Ways to adjust text color after clicking on an element

Just a heads up, I didn't write all of the web-page code so I'm not exactly sure what pdiv is. But I want to see if I can fix this small issue [making text color change when clicked on to show which section you're reading].

This particular section looks like this:

https://i.sstatic.net/EDem4.png

and when you click on it, it will display all menu sections:

https://i.sstatic.net/WTa4o.png

function menuShowPol(pdiv){
  
          if(document.getElementById('menu_pol_div'+pdiv).
                                        style.display=="none") { 
          document.getElementById('menu_pol_div'+pdiv)
                              .style.display = "inline-block";
      } else {
          document.getElementById('menu_pol_div'+pdiv)
                                      .style.display = "none";
      }
      }
      function changeColor(pdiv){
      {
        document.getElementById('menu_pol_div'+pdiv)
                          .style.color = "#ff0000"; // forecolor
        document.getElementById('menu_pol_div'+pdiv)
                 .style.backgroundColor = "#ff0000"; // backcolor
      }
  
          
 if($showpol==1){
        $menutext .= "<div id=\"country_menu_report_name\"
                        onclick=\"menuShowPol('".$pol."');
                        changeColor('".$pol."'); return 
                                  false;\">".$thispol."</div>\n";

Is there any way to achieve this using only CSS? Or if JavaScript is required, can you offer some assistance? Thank you.

Answer №1

If you pass "this" to your events, it will provide direct access to the element that was interacted with. Here's a simple version (as suggested by others, using CSS classes for different div states is recommended).

Take note of the onclick="changeColor(this)" in the header divs. Additionally, I connected country_menu_report_X to menu_pol_X, which may not be the best practice, but it gets the job done and is basic.

function changeColor(pdiv){
   var myid = pdiv.id;
   var otherid = myid.replace("country_menu_report_", "menu_pol_");
   var otherdiv = document.getElementById(otherid);
   var toggle = otherdiv.style.display == "none";
   if(!toggle){
       pdiv.style.color = "#0000ff"; // forecolor
       pdiv.style.backgroundColor = "#ccccff"; // backcolor
      otherdiv.style.display = "none";
   }else{
       pdiv.style.color = "#000000"; // forecolor
       pdiv.style.backgroundColor = "#aaeeaa"; // backcolor
       otherdiv.style.backgroundColor = "#ccffcc"; // backcolor
       otherdiv.style.display = "block";
   }
}
<div id="country_menu_report_a" onclick="changeColor(this)" style="user-select:none; cursor:pointer; color:#0000ff; background-color:#ccccff;" >test div A. click me</div>
<div id="menu_pol_a"style="display:none" >menu item A</div>
<div id="country_menu_report_b" onclick="changeColor(this)" style="user-select:none; cursor:pointer; color:#0000ff; background-color:#ccccff;" >test div B. click me</div>
<div id="menu_pol_b" style="display:none" >menu item B</div>

Answer №2

From my perspective, I believe When attempting to click the button

$menutext .= "<div id=\"country_menu_report_name\" onclick=\"menuShowPol('".$pol."');changeColor('".$pol."'); return false;\">".$thispol."</div>\n";

The function should target the exact same button

Check the function that is searching for an element with the ID:

document.getElementById('menu_pol_div'+pdiv).style.display = "inline-block";

You must search for the same ID in this line:

document.getElementById('country_menu_report_name\')

or $menutext .= "".$thispol."\n";

and ensure that "pvid" is included in the ID: for example

for

$menutext .= "<div id=\"country_menu_report_name\" onclick=\"menuShowPol('".$pol."');changeColor('".$pol."'); return false;\">".$thispol."</div>\n";

you can use:

pvid = "report_name\"
document.getElementById('country_menu_'+pvid)

Answer №3

In my approach, I define two CSS classes as follows:

.read{
   color: red;
}

.unread {
   color: blue;
}

To implement this, my code would look something like this:

function changeColor(currentDiv){
    // Remove 'read' class from all divs.
    var divs = document.getElementsByClassName('read');
    for(var i=0; i<divs.length; i++){
        divs[i].classList.remove('read');
    }
    // Add 'read' class to the current div.
    currentDiv.classList.add('read');
}

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

AngularJS supports asynchronous validation on blur

Using Angular JS version 1.5.6, I am looking to implement asynchronous input validation that occurs only on blur. However, I am unable to use modelOption: {debounce: 500} or modelOption: {updateOn: 'blur'} due to the directive being used with oth ...

Transform or retrieve information from input into unformatted text

I'm working on a JavaScript function that can convert input values to text. However, I am facing an issue as I only want to convert data from one specific row into plain text. Each row in my table has 5 cells along with a button for saving the data. I ...

Learn the process of automatically copying SMS message codes to input fields in Angular17

After receiving the first answer, I made some changes to the code. However, when testing it with Angular, I encountered several errors. How can I resolve these issues? TS: async otpRequest() { if ('OTPCredential' in window) { const ab ...

The app is having trouble loading in Node because it is unable to recognize jQuery

I am currently using Node to debug a JavaScript file that includes some JQuery. However, when I load the files, the $ sign is not recognized. I have installed JQuery locally using the command npm install jquery -save-dev. The result of "npm jquery -versio ...

What is the best way to determine if two external values are equal within a mongodb criteria object?

Consider the following collection: {id: 1, name:"abc"}, {id: 2, name:null} When testing a property, I typically use this method: db.collecton.find({name:"abc"}, {name:1}); // This will return the first document. Now, I want to incorporate two external ...

Guide on sending a message to a specific channel using Discord.js version 13 with TypeScript

After recently diving into TypeScript and seeing that Discord.js has made the move to v13, I have encountered an issue with sending messages to a specific channel using a Channel ID. Below is the code snippet I am currently using: // Define Channel ID cons ...

Extract information from a JSON string and present it on the screen

I am a complete novice when it comes to D3 (with very little experience in JS). Here are the lines of code I am working with: <script type='text/javascript'> data ='{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.62,"qsec":16. ...

A guide to activating an input field based on the value of another input field in AngularJs

An AngularJs form requires the user to input the number of hours worked. If the value entered is 0, an additional question should be displayed for the reason why no work was done. <label>Hours worked:</label> <input ng-model="hours" type="n ...

What is the method for retrieving a value with a designated key?

An array has been created from JSON source using the $.each method. The console displays the following: $vm0.sailNames; [Array(24), __ob__: Observer] (Interestingly, jQuery seems to have created an Observer) In the Vue.js development view, it appears li ...

The HTML table fails to refresh after an Ajax request has been made

I am currently utilizing Ajax to delete a row from the Roles table. The functionality allows the user to add and delete roles using a link for each row. While the deletion process works properly and removes the row from the database, the table does not get ...

Looking for a skilled JavaScript expert to help create a script that will automatically redirect the page if the anchor is changed. Any t

Seeking a Javascript expert, In my custom templates, I have used a link as shown below: <a href='http://www.allbloggertricks.com'>Blogging Tips</a> I would like the page to redirect to example.com if the anchor text is changed from ...

How to showcase base64 encoded images in pug (jade) with node.js

Can anyone help with decoding this mysterious data and displaying the image? I'm using pug as my template engine. Below is the questionable data that needs to be shown as an image: /9j/4AAQSkZJRgABAQEAYABgAAD/4QBaRXhpZgAATU0AKgAAAAgABQ ...and so f ...

ReactJS - Unable to access property of undefined object

I encountered a TypeError when rendering, stating that my object is not defined. Despite thinking I defined it before using it. Here is an example of ArticleDetails.js that I am referencing: import React, {Component} from 'react'; class Arti ...

Stop the back button from working on a jQuery Mobile webpage

I'm currently developing a project using jQuery mobile and I need to restrict the user from navigating back to certain pages. While the UI does not have a back button in these instances, I am facing an issue when the user clicks the browser's bac ...

By employing the $watch method, the table disappears from the div element

I've integrated the isteven-multi-select directive for my multi-select dropdown functionality. By providing it with a list of thingsList, it generates a corresponding checkedList as I make selections. Initially, I used a button to confirm the selecti ...

Migration processes encountering delays due to running nodes

When running migrations in Node, I am encountering a timeout error. The specific error message is: Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. Here is the ...

I am in need of a customized 'container' template that will display MyComponent based on a specific condition known as 'externalCondition'. MyComponent includes the usage of a Form and formValidation functionalities

container.html <div ngIf="externalCondition"> <!--Initially this is false. Later became true --!> <my-component #MyComponentElem > </my-component> <button [disabled]= "!myComponentElemRef.myDetailsF ...

The Angular Universal error arises due to a ReferenceError which indicates that the MouseEvent is not

I am encountering an error while trying to utilize Angular Universal for server-side rendering with the command npm run build:ssr && npm run serve:ssr. This is being done in Angular8. /home/xyz/projects/my-app/dist/server/main.js:139925 Object(tslib__WEB ...

Guide to executing API PATCH request on the server for a system that approves outings?

I have developed a system for approving outings using the MERN Stack. I wrote code to change the leave status to "Approved", but the changes are not saved when I refresh the page. The PATCH request works fine through Postman. Mongoose Schema Snippet for l ...

What's the best way to constrain a draggable element within the boundaries of its parent using right and bottom values?

I am currently working on creating a draggable map. I have successfully limited the draggable child for the left and top sides, but I am struggling to do the same for the right and bottom sides. How can I restrict the movement of a draggable child based o ...