All about the ins and outs of JavaScript and manipulating the

I attempted to use DOM manipulation to change the page background color and div background color by utilizing getElementById and onclick methods. I wrote some code to make this happen, but unfortunately, it did not work as expected.

Can anyone identify what's causing the issue in my code?

Any suggestions on how to fix it?

HTML

<html lang="en">
<head>
    <mate charset="utf-8" />
    <title>change color</title>
    <link rel="stylesheet" href="test.css" />
</head>

<body>
    <div id="test">
        <a href="javascript:void(0);" id="bodyColor">change body background-color</a>
        <a href="javascript:void(0);" id="divColor">change div background-color</a>
    </div>
<script src="test.js"> </script>
</body>
</html>

CSS

body *{
margin: 0;
padding: 0;
}

a{
    display: block;
    color: white;
    background-color: red;
    width: 200px;
    text-align: center;
    font-weight: bold;
    margin: 150px auto;
    text-decoration: none;
}

#test{
    border: 1px solid black;
    width: 500px;
    margin: 0 auto;
}

JavaScript

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function bodyBackgroundColor() {
    var color = document.getElementById('bodyColor');
    color.onclick = function(){
        body.style.backgroundColor = "red";
    }
}

function divBackgroundColor() {
    var color = document.getElementById('divColor');
    var divColor = document.getElementById('test');
    color.onclick = function(){
        divColor.backgroundColor = "red";
    }
}

addLoadEvent(bodyBackgroundColor);
addLoadEvent(divBackgroundColor);

Answer №1

When setting the background color in bodyBackgroundColor, don't forget to include document. before body since body is not a global element:

document.body.style.backgroundColor = "red";

In the case of divBackgroundColor, make sure to add .style. before setting the background color:

divColor.style.backgroundColor = "red";

Instead of using the complex addLoadEvent function, consider moving your script tag to the end of the page, just before the closing </body> tag. This ensures that all elements on the page will be loaded when attempting interaction. For more tips, refer to the YUI Best Practices for Speeding Up your Website.


To troubleshoot these issues, utilize the built-in debugger available in most modern browsers. You can access it by pressing F12 or Ctrl+Shift+I, or through the browser's menu under "Dev Tools". The debugger allows you to view the source code of your page, set breakpoints, single-step through code execution, inspect variables, and more.

A fundamental feature of the debugger is the console, where errors and other information are displayed.

Answer №2

Finally, the issue has been resolved!

XHTML

<!DOCTYPE XHTML>
<html lang="en-US>
<head>
    <mate charset="utf-8" />
    <title>Color Change</title>
    <link rel="stylesheet" href="styles.css" />

</head>

<body>
    <div id="test">
        <a href="javascript:void(0);" id="bkgColor">Change background color of body</a>
        <a href="javascript:void(0);" id="boxColor">Change background color of div</a>
    </div>
    <script src="scripts.js"> </script>
</body>
</html>

CSS Styles

body *{
    margin: 0;
    padding: 0;
}

a{
    display: block;
    color: white;
    background-color: red;
    width: 200px;
    text-align: center;
    font-weight: bold;
    margin: 150px auto;
    text-decoration: none;
}

#test{
    border: 1px solid black;
    width: 500px;
    margin: 0 auto;
}

Javascript Logic


function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function changeBackgroundColor(){
    var bkgColor = document.getElementById('bkgColor');
    bkgColor.onclick = function(){
        document.body.style.backgroundColor = "red";
    }

    var boxColor = document.getElementById('boxColor');
    var selectedBox = document.getElementById('test');
    boxColor.onclick = function(){
        selectedBox.style.backgroundColor = "blue";
    }
}

addLoadEvent(changeBackgroundColor);

You can also try this simplified approach:

XHTML

<!DOCTYPE HTML>
<html lang="en">
<head>
    <mate charset="utf-8" />
    <title>change color</title>
    <link rel="stylesheet" href="test.css" />

</head>

<body>
    <div id="test">
        <a href="javascript:void(0);" id="bodyColor">change body background-color</a>
        <a href="javascript:void(0);" id="divColor">change div background-color</a>
    </div>
    <script>
    function bodyBackgroundColor(){
        var color = document.getElementById('bodyColor');
        color.onclick = function(){
            document.body.style.backgroundColor = "red";
        }
    }

    function divBackgroundColor(){
        var color = document.getElementById('divColor');
        var divColor = document.getElementById('test');
        color.onclick = function(){
            divColor.style.backgroundColor = "blue";
        }
    }

    window.onload = bodyBackgroundColor();
    window.onload = divBackgroundColor();
    </script>
</body>
</html>

CSS Styles

body *{
    margin: 0;
    padding: 0;
}

a{
    display: block;
    color: white;
    background-color: red;
    width: 200px;
    text-align: center;
    font-weight: bold;
    margin: 150px auto;
    text-decoration: none;
}

#test{
    border: 1px solid black;
    width: 500px;
    margin: 0 auto;
}

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

Establishing limits for a division using keyboard commands

Alright, I've decided to remove my code from this post and instead provide a link for you to view it all here: (please disregard any SQL errors) If you click on a Grid-Node, the character will move to that position with boundaries enabled. Draggi ...

Using jQuery's .html() method will remove the selected attribute from the dropdown menu option

When generating HTML dynamically, a select element is included. After choosing an option inside it, everything works fine. For example: <div id="test"> <select> <option value="1">1</option> <option value="2" selec ...

Single-line form with labels positioned above the input fields

For my web app project, I am using AngularJS and Bootstrap 3 for CSS (although my CSS knowledge is limited). I am trying to design an inline form with 5 input fields and labels positioned on top of them. The first field should take up more space than the o ...

I am experiencing difficulty getting my component to properly implement the bootstrap NavBar and NavIcon styles

I am new to using bootstrap with react and I am facing an issue where the dimensions are not being applied to my Navbar and Navbar Icon. I have already installed dependencies and used className instead of class, but still no changes are visible. import Re ...

Filtering an array dynamically by utilizing an array of conditions

Can jQuery-QueryBuilder be used to filter an array? This amazing plugin generates a unique array of conditions: condition:"AND" rules: { field:"name" id:"name" input:"select" operator:"equal" type:"string" value:"Albert" } I have ...

Obtain the beginning and ending positions of a substring within a larger string

As a beginner in the world of AngularJS and web development, I am faced with a challenge. I have a specific string that is currently selected on a tab, like so: var getSelectedText = function() { var text = ""; if (typeof window.getSelection !== "un ...

Any suggestions on how to avoid code repetition using Jquery?

This code allows me to create a menu for my gallery. By setting the .masonry # elements to display:none, I can use the corresponding ID in the menu to show the correct gallery when clicked. However, there is a lot of repetitive code in this implementatio ...

Not all words are compatible with word-wrap, don't you think?!

I have a situation where I used the following CSS properties for a div: word-wrap: break-word; text-align: justify; When a single word is too long to fit within the width of the div, it wraps or breaks into multiple lines. However, if a second word with ...

Retrieve the Nth class of an element that has multiple classes without relying on the .attr("class") method in jQuery

Within a container with two styles, the initial nested div <div class="datacheck"> <div class="classic_div_data customdataid_305"> some values are included here </div> <div class="optiondiv"> </div> </div& ...

Utilizing inputRef in conjunction with MUI's useAutocomplete

Is there a way to pass the "inputRef" to Material UI's useAutocomplete? I'm looking to set a custom reference on the input, but the getInputProps() method from useAutocomplete already requires its own reference. I've attempted various appr ...

The jst.js error in sails JS template indicates that the variable _ cannot be found

I am brand new to the world of programming and am currently diving into JavaScript and Sails JS. I must admit, I am enjoying the learning process so far, but recently encountered a problem that has left me scratching my head. Please bear with me as I may n ...

How to retrieve a Facebook user access token using server-side scripting with Node.js

I am looking to retrieve my Facebook ad campaign statistics every 30 minutes using Nodejs. To accomplish this, I require a user access token that needs to be refreshed for every request due to expiration. Any suggestions on how I can achieve this solely ...

Angular JS Introductory Module

Currently, I am encountering an issue in AngularJS 1.2.15 marked by $injector:modulerr. Interestingly, the application runs smoothly when hosted on a MAMP Apache server locally, but encounters errors when running on a node server, generating the error mess ...

Determine the div's width inside the viewport

I am trying to determine the width of a div within the viewport. When using .css(width) on my div, it calculates the overall width instead. Here is the code I am currently using: var $Windowwidth = $(window).width(); var $lefty = $("#gallerytop"); var $G ...

The functionality of the ui sortable feature in Angular is not effective when used on a single-page website

My latest project involves using a single-page application. To connect the UI Angular library, I followed these steps: I started by adding the necessary scripts: <script src=.....jquery-1.9.1.js"></script> <script src=.....jquery-ui.js"> ...

Leaflet setStyle changes are effective when applied through the console but do not reflect in the actual

I currently have a map with around 1000 polygons that I am loading onto it. My goal is to color these polygons based on a specific property value. The code snippet below showcases my approach, but the results are not as expected. mapLayerFieldGrid = new L ...

Update the link by simply clicking on a div tag

I am currently working on a PHP page and my goal is to add the extension ?id=variable_value to its URL when I click on a specific div. However, whenever I try to do this, it shows me an error message stating that the URL with the extension is undefined. B ...

The Art of Dynamic Component Manipulation in Angular

The current official documentation only demonstrates how to dynamically alter components within an <ng-template> tag. https://angular.io/guide/dynamic-component-loader My goal is to have 3 components: header, section, and footer with the following s ...

Is there a way to determine if a React functional component has been displayed in the code?

Currently, I am working on implementing logging to track the time it takes for a functional component in React to render. My main challenge is determining when the rendering of the component is complete and visible to the user on the front end. I believe t ...

What is the best way to attach an image to the image section coming from the backend in vue.js?

I have developed a frontend page that displays a list of books, with the data coming from the backend. The backend response includes image files, and I am struggling to bind these images to the image section of my template. I have the image paths from the ...