Assign individual buttons to specific CSS files to update the background image on my webpage

I'm experimenting with changing the background of my webpage using Angular framework. I want to switch between different CSS files by clicking on buttons within the same page.

CSS1.css

body {
     background-image: url("./Images/mg.jpg");
}

CSS2.css

body {
     background-image: url("./Images/mg.jpg");
}

I have created two buttons in the HTML file, where clicking on button1 should load CSS1.css and clicking on button2 should load CSS2.css.

I tried to assign an ID to each button and map a script function to them, but encountered a runtime error.

HTML File

<button type="button" id="button1" onclick="myFunction()">background1</button>

<link rel="stylesheet" type="text/CSS" href="CSS1.css" id="theme">

Script file

function myFunction()
{   
document.getElementById("button1")= document.getElementById("theme");
}

Can someone please guide me on where I may have gone wrong here? Thanks.

Answer №1

When it comes to loading stylesheet links, they work instantly without requiring any custom Javascript for application.

If you wish to obtain a specific effect, you can simply eliminate the link tags and update the function as follows:

function adjustStyle() {   
    document.body.style.background = "url('./Images/mg.jpg')";
}

Answer №2

When using the getElementById() method, it will retrieve the element that matches the specified value of the ID attribute.

If we have both left side

document.getElementById("button1")
and right side returning a value, this would not be permissible as each ID should be unique within the document.

Answer №3

One possible solution is to implement the following:

HTML

<link rel="stylesheet" href="CSS1.css" id="theme">

<button type="button" (click)="myFunction('CSS1.css')"> background1 </button>
<button type="button" (click)="myFunction('CSS2.css')"> background2 </button>

Pro Tip: It's important to note the use of (click) instead of onclick. As you mentioned angular in your tags, it's recommended to utilize this attribute when working with angular.

TypeScript

myFunction(sheet: string) {
    document.getElementById('theme').setAttribute('href', sheet);
}

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

Struggling to align a div vertically using CSS is causing me some difficulties

Hey there, I'm trying to figure out how to align the "container2" div to the bottom of the "container," but I'm running into some issues. Can anyone lend a hand? HTML <div id="container"> <div id="container2"> ...

Error while conducting unit testing: Element 'X' is unrecognized

While running the command npm run test, I encountered a specific error in my terminal: 1. If 'app-general-screen' is an Angular component, then verify that it is a part of an @NgModule where this component is declared. 2. If 'app-general-sc ...

Leveraging Vue.js's computed properties to access and manipulate elements within an

I have a simple template that displays text from a wysiwyg editor using two-way data binding, as shown below: <template> <div> <quill-editor v-model="debounceText" :options="editorOptionProTemplate" > </qu ...

The function validateLogin is not defined within the code, resulting in a javascript exception being

Hey there, I'm encountering an undefined function error and I believe my code is correct. Can someone please offer assistance in this situation? Additionally, could you recommend a good tutorial for fetching data through a webservice using the Ajax me ...

What is the best way to notify the user if the percentage entered is not a numeric value?

My role is to notify the user when the entered value exceeds the acceptable range: if (document.myForm.outputPercentage.value <= 0 || document.myForm.outputPercentage.value >= 100) { alert( "Please enter a percentage between 1 and 100 ...

Having trouble with TypeScript Library/SDK after installing my custom package, as the types are not being recognized

I have created my own typescript library using the typescript-starter tool found at . Here is how I structured the types folder: https://i.stack.imgur.com/igAuj.png After installing this package, I attempted a function or service call as depicted in the ...

Is there a method to categorize an array of objects by a specific key and generate a new array of objects based on the grouping in JavaScript?

Suppose I have an array structured like this. It contains objects with different values but the same date. [ { "date": "2020-12-31T18:30:00.000Z", "value": 450 }, { "date": "20 ...

When using VSCode for Next.js projects, automatic imports from "react" are not supported

* While similar, this question is not a duplicate of this other question; the solutions provided there are tailored for TypeScript and do not seem to apply to JavaScript. In my current project using Next.js in Visual Studio Code, I am facing an issue wher ...

Creating dynamic HTML elements for each section using JavaScript

Is there a way to dynamically add a task (input + label) for each specific section/div when entering the name and pressing the "Add" button? I attempted to create an event for each button to add a task for the corresponding div of that particular section, ...

Determine a comparative measurement using specific numerical values

I am currently in the process of creating a webpage and I want to ensure that it is responsive by adjusting certain values based on the width of the viewport. Specifically, I have a DIV element that I want to split into 2 columns. For smaller screens (min ...

Regular expression designed to admit only a maximum of two underscore characters, as well as no other special characters, with the condition that the character prior or

Looking for a specific format within a string, such as SOM_P9ERR96M27VP4_PL. The conditions are: must have exactly two underscores, not at the beginning or end of the string, and no other special characters like "&*$," following the underscore. Additiona ...

Creating an object using a string in node.js

I have a string that I am sending from AngularJS to NodeJS in the following format. "{↵obj:{↵one:string,↵two:integer↵}↵}" //request object from browser console To convert this string into an object and access its properties, I am using the serv ...

Exploring the Nested Components Feature in Ionic 4

I am currently in the process of transitioning my application from Ionic 3 to Ionic 4, and I have noticed that async and await calls are now being used for each component. While I understand the reasoning behind this change, in my Ionic 3 app, I had a nest ...

Is it possible to include a div above a centered image?

Currently I am working with ImageFlow and I would like to overlay a div on top of the image when it is clicked, sliding it into the center. I have been looking through the JavaScript file but the function MoveIT() seems to be called multiple times and I am ...

Issue with hidden.bs.modal event not triggering in Bootstrap

Even after using the hidden.bs.modal event, it still doesn't seem to work for me. I have attempted to implement the code below, but unfortunately, it's not functioning as expected. Any guidance on what I should try next would be greatly appreciat ...

The click function for the parent div will not be executed if I click on the child div

Hey, I encountered an issue in my code that I need help with. $(document).ready(function() { $(document).on('click', '.rohit', function() { alert('rohit'); }) $(document).on('click', '.azad', ...

The Angular client fails to receive data when the SignalR Core Hub method is called from the Controller

Issue with Angular SignalR Client not Receiving Data from ASP.NET API I have a setup where an angular website is connected to an asp.net back-end using SignalR for real-time data service. Everything was working fine when tested in localhost, but after pub ...

Sending HTML parameters to a PHP file

I have been trying to pass the parameters from the current HTML page to a PHP page using a form. In my header in the HTML, I currently have the following function: <script> function getURLParameter(name) { return decodeURIComponent((new Re ...

Rejuvenate a just-launched window.open starting from the about:blank

After receiving data from an ajax result, I am trying to open a pdf in a new window. However, the pdf viewer is only displayed if I manually resize the window (using manual hotspot resizing). How can I ensure that the contents display properly in its popu ...

What are some creative ways to design the mat paginator in Angular?

Looking for tips on how to style Angular Material Paginator to match a Figma design? ...