Javascript: Altering Link Color

After creating my own webpage with a unique light switch that inverts colors, I encountered an issue with changing the color of my links. Despite setting the anchor tags to transition to a different color, it just wouldn't work.

Here is the HTML code snippet:

<nav>
    <h1>My Portfolio</h1>
    <ol>
        <li><a title="Link to My Cover Letter & CV" href="index.html">My Cover Letter & CV</a> | </li>
        <li><a title="Link to My Projects" href="">My Projects</a> | </li>
        <li><a title="Link to Temp" href="">Temp</a> | </li>
        <li><a title="Link to Temp" href="personalDev.html">Temp</a></li>
    </ol>
</nav> <!-- Closes Nav -->

The CSS styling for the links:

/*Links*/
a, a:link, a:visited {
    color: black;
    text-decoration: none;
    transition: 1s;
}

/*Link hovering*/
nav a:hover {
    text-decoration: none;
    border: solid 1px black;
    border-radius: 5px;
    padding: 10px;
}

As for JavaScript functionality:

document.addEventListener ("DOMContentLoaded", handleDocumentLoad);
function handleDocumentLoad() {

    var offSwitch = document.getElementById("lightSwitchOff"); 
    var onSwitch = document.getElementById("lightSwitchOn"); 
    var border = document.getElementById("mainContent"); 
    offSwitch.innerHTML = "Turn On Night Mode";
    onSwitch.innerHTML = "Turn Off Night Mode";
    onSwitch.style.display = "none";

    offSwitch.addEventListener("click", lightsOff); 
    onSwitch.addEventListener("click", lightsOn); 

    function lightsOff() { 
        document.body.style.backgroundColor = "#000000";
        document.body.style.color = "#FFFFFF";
        border.style.borderColor = "#FFFFFF";
        onSwitch.innerHTML = "Turn Off Night Mode";
        onSwitch.style.display = "inline";
        offSwitch.style.display = "none";
    }

    function lightsOn() { 
        document.body.style.backgroundColor = "#FFFFFF";
        document.body.style.color = "#000000";
        border.style.borderColor = "#000000";
        offSwitch.innerHTML = "Turn On Night Mode";
        onSwitch.style.display = "none";
        offSwitch.style.display = "inline";
    }
}

Additionally, I am curious about preserving the page state so that if a user toggles the light switch and refreshes the page, it remains in the same mode.

Answer №1

Why not apply styles directly to the DOM elements?

<button id="btn" type="button">Click me</button>
<script>
    document.getElementById("btn").style.backgroundColor = "blue";
</script>

Alternatively, you could achieve the same with jQuery:

<button id="btn" type="button">Click me</button>
<script>
    $( "button" ).css( {"background-color":"blue"} );
</script>

Answer №2

document.addEventListener ("DOMContentLoaded", handleDocumentLoad);

function handleDocumentLoad() {

//Variable
var offSwitch = document.getElementById("lightSwitchOff"); //Targets div with ID lightSwitchOff
var onSwitch = document.getElementById("lightSwitchOn"); //Targets div with ID lightSwitchOn
var border = document.getElementById("mainContent"); //Targets the mainContent
offSwitch.innerHTML = "Turn On Night Mode";
onSwitch.innerHTML = "Turn Off Night Mode";
onSwitch.style.display = "none";

//Event Listener
offSwitch.addEventListener("click", lightsOff); //When clicked this action is performed
onSwitch.addEventListener("click", lightsOn); //When clicked this action is performed


var links = document.getElementsByClassName("links");


//Function
function lightsOff() { /*This changes the background colour to black and makes text white*/
document.body.className += " body_lights_off";
border.style.borderColor = "#FFFFFF";
onSwitch.innerHTML = "Turn Off Night Mode";
onSwitch.style.display = "inline";
offSwitch.style.display = "none";
var i;
for(i = 0; i < links.length; i++) {
links.item(i).className += " links_lights_off";
}
}

function lightsOn() { /*This changes the background colour to a white and makes text black*/
document.body.className = document.body.className.replace(" body_lights_off", "");
border.style.borderColor = "#000000";
offSwitch.innerHTML = "Turn On Night Mode";
onSwitch.style.display = "none";
offSwitch.style.display = "inline";
var i;
for(i = 0; i < links.length; i++) {
links.item(i).className = links.item(i).className.replace(" links_lights_off", "");
}
}


}
.body_lights_off {
background-color: #000000;
color: #ffffff;
}

/*Links*/
a, a:link, a:visited {
    color: black;
    text-decoration: none;
    transition: 1s;
}

/*Link hovering*/
nav a:hover {
    text-decoration: none;
    border: solid 1px black;
    border-radius: 5px;
    padding: 10px;
}

.links_lights_off:link, .links_lights_off:visited {
color: white;
}
<nav>
    <h1>My Portfolio</h1>
    <ol>
        <li><a class="links" title="Link to My Cover Letter & CV" href="index.html">My Cover Letter & CV</a> | </li>
        <li><a class="links" title="Link to My Projects" href="">My Projects</a> | </li>
        <li><a class="links" title="Link to Temp" href="">Temp</a> | </li>
        <li><a class="links" title="Link to Temp" href="personalDev.html">Temp</a></li>
    </ol>
</nav> <!-- Closes Nav -->

<button id="lightSwitchOn"></button>
<button id="lightSwitchOff"></button>

<div id="mainContent"></div>

You assign a class named links to each link, then use document.getElementsByClassName to select all elements with that class in JavaScript. Within the functions lightsOff and lightsOn, you loop through the links elements using links.item([index]) syntax, applying effects by adding or removing the links_lights_off class defined in CSS for changing link colors.

A similar approach is used for changing the background color and text color of document.body with the body_lights_off class. This class is added in the lightsOff function and removed in the lightsOn function to achieve the desired effect.

While there are potential enhancements possible, introducing too many at once could lead to confusion. Feel free to ask if you have any questions or if you're looking for a different outcome.

If you need further clarification or modifications, don't hesitate to reach out. Thank you!

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

Group in group, glitch in outdated browser

Facing an issue with IE6 while writing HTML/CSS code. I am looking to create dynamic divs using classes: Here is a simple example (not real-project code): .top {width: 50px;} .top.selected {background: #f00;} .mid {width: 114px;} .mid.selected {backgrou ...

What is the best way to manage a group of checkboxes using EJS?

I am currently utilizing ejs for my website pages and on one particular page, I have an array of objects. The number of objects in the array is not known when the page initially loads. This page allows me to edit a series of announcements and I would like ...

Issue with AJAX not receiving successful response after function invocation

I am trying to dynamically load data based on the specific URI segment present on the page. Below is my JavaScript code: $(document).ready(function() { $(function() { load_custom_topics(); }); $('#topics_form').submit(funct ...

GSAP also brings scale transformations to life through its animation capabilities

I have an SVG graphic and I'm looking to make four elements appear in place. I've been using GSAP, but the elements seem to be flying into place rather than scaling up. Here's the code snippet I've been using: gsap.fromTo( ...

What is the best way to include an uncomplicated HTML Element alongside a touch of JavaScript?

I'm facing an issue with WordPress. Due to security concerns, I cannot use the script tag directly within WordPress, so I have uploaded it to a separate server. My query is whether I can display the content from that link as a small widget on my WordP ...

when successful, refresh the page

I am currently utilizing the following javascript code to load recrefresh.php when the page first loads. Upon executing the ajaxvote function, I aim for the subsequent div to be refreshed: <div class="recrefresh"></div> After attempting to ad ...

What is the priority of the asset pipeline's execution order?

What is the priority of asset pipeline? I am trying to replace a part of ace.css style with user.css.scss. The stylesheet file ace.css in the vendor folder should be overridden by user.css.scss. However, it did not work as expected even when I included ...

Issues with Google Fonts failing to load correctly

Would you mind taking a look at this issue for me? In all browsers except Firefox, the expected behavior is that a web font remains invisible until fully loaded, preserving space on the page. Interestingly, in Chrome and IE9 (the browsers I tested), ther ...

What is the best way to ensure that a <label> remains vertically aligned with its <form>?

I'm struggling to incorporate their suggestions into my design. How can I align my label to the left of my input field on the same line? Also, I'm a beginner in coding so please excuse any mistakes in my code: body { background-color: #f5f ...

Is there a way to create an internal link to another HTML templating engine page within Express.js?

I am currently facing an issue with two Pug files, index.pug and search.pug, stored in a /views folder. In my index.pug file, I have the following line of code: a(href="/search.pug") Search In my JavaScript file, I have specified the view engine as P ...

Field for text input enclosed within the <select> tag

I have a project where I am implementing a dropdown using AngularJS. Here is the code snippet: <div class="col-md-9"> <input type="text" placeholder="Enter Module" list="names" ng-model="data.Name" /> <select id="names" class ...

Creating redux reducers that rely on the state of other reducers

Working on a dynamic React/Redux application where users can add and interact with "widgets" in a 2D space, allowing for multiple selections at once. The current state tree outline is as follows... { widgets: { widget_1: { x: 100, y: 200 }, widg ...

Trouble encountered in PHP: Generating a file from POST data and initiating download prompt for the user not functioning as intended

On my webpage, users fill out forms and input fields, which are then sent to a PHP page via Ajax and $_POST. The PHP file successfully writes the output to a txt file. However, I'm facing an issue trying to prompt the user to download the file on the ...

What is the appropriate semantic to apply to the members of a search result list?

I have an image that illustrates my goal: https://i.sstatic.net/xDLRA.png The "Search Results" Title is a h2 in terms of semantics. The "Search Result Title 2018" would be a h3. My query pertains to how the elements "Date & Time", "Fees", "Credit", an ...

Having trouble adding an image link to the navbar using bootstrap?

I am experiencing an issue where the image in the provided code is not displaying. Interestingly, when I remove the alt attribute, it shows up as a broken link. This problem persists even when I try using different images or links to images. As someone wh ...

Ensuring that an object attribute is assigned to $watch in AngularJS to activate triggering

As a newcomer to AngularJS, I recently attempted the following code: <div ng-controller="ctrl1"> <div ng-controller="ctrl2"> <select ng-model="myvar" ng-options="c for c in vars" ></select> <div>{{myvar}} ...

Exploring MessageEmbed Properties

I am trying to retrieve the description of this Message embed. So far, I have used console.log(reaction.message.embeds) which displays the information below. However, when I attempt to access the description directly with console.log(reaction.message.embe ...

Guide on how to show every property of each object in an array

I have an array of words stored as objects and I am looking to showcase all the properties associated with each word. While only two words are shown here, there are actually many more in the array. const words = [ { word:'interrogate' meaning:&ap ...

How can I display a button (hyperlink) on a new line using CSS or jQuery?

I am looking to create a new line after the last input of my form. On this new line, I want to add a "remove-link". This is my HTML: <div class="subform dynamic-form"> <label for="id_delivery_set-0-price"> Price: </label> <inp ...

The functionality of Bootstrap's push and pull options appears to be malfunctioning

Exploring the grid option pull and push has presented some challenges for me. I suspect the issue lies in my implementation of bootstrap CSS and/or JS (not certain if push/pull are controlled by JS or CSS). I've included a push-pull setup at the top ...