Use javascript to change style

Javascript Change HTML Element Styles Tutorial

In this Javascipt tutorial we learn how to change HTML element styles with Javascript by accessing the style object.

We also discuss some rules when working with the style object and its properties.

How to change HTML element styles

Now that we know how to select HTML elements , we can perform several types of operations on them.

For example, we can manipulate and change HTML element styles with Javascript by tapping into the style object of the selected element.

The style object contains all the CSS properties we need to change a specific style on an element.

    In the example above, we change the color property of the heading and add a background color and some padding to the paragraph.

Every style can be changed from Javascript, however the property names might look a little different from what we’re used to.

As mentioned in the Variables & Constants lesson , Javascript naming conventions tend to use camel case. Any properties with multiple words will use camel case instead of the dash operator.

   Another important point is that the property values must be specified as strings. If we don’t use a string, the property won’t change and Javascript will raise an error.
 The example above doesn’t use a string when trying to change the font size, so Javascript raises an error.
 Uncaught SyntaxError: Invalid or unexpected token

The error is a little confusing but basically it means that Javascript was expecting a » from the beginning of a string, but got something else instead.

So, if a property has multiple words, converting from CSS to Javascript is easy.

How to add & remove classes

When working with HTML, CSS and Javascript, we typically want a separation of concerns. What this means is that we want to separate the structure (HTML), style (CSS) and behavior (Js) from each other.

We shouldn’t change styles directly from Javascript. That would combine style and behavior, which is considered a bad practice.

Instead, we write classes in CSS and add them to an HTML element with Javascript with the classList property.

  • classList.add() will add the specified class to a selected element.
  • classList.remove() will remove the specified class from a selected element.
  • classList.toggle() will add/remove the specified class when invoked.

The add() method takes the class name we want to add as an argument.

    In the example above, the ‘.hidden’ class will hide whichever element it’s attached to. In the hide() function we tell Javascript that we want to add this class to the div element.

In the last statement we add an event listener to the button that will invoke the hide() function when the button is clicked.

If you don’t know about event listeners, don’t worry about it for now. We cover them later on in the Event Listeners lesson .

We can also remove a class from an element with the remove() method. This method takes the class name we want to remove as an argument.

Источник

How To Change CSS With JavaScript [With Examples]

JavaScript is all about dynamic stuff and dealing with dynamic CSS changes is just one of the scenarios where JavaScript is exactly what we need.

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.

How To Modify CSS With JavaScript - Best Ways

Let’s get into the different ways we can do achieve this:

1. Change CSS inline properties with JavaScript

Setting individual styles directly from JavaScript is one of the most common scenarios when dealing with dynamic CSS styles.

This way allows you to change the CSS styles for one or multiple elements present in the DOM.

const element = document.querySelector('.demo');
element.style.backgroundColor = 'red';

Notice that when setting the CSS styles using the style property you have to write the CSS properties in camelcase. Instead of using a dash — to separate the words you will have to write in capitals the first letter of each word. ( backgroundColor , fontSize )

If you execute this code just like this, you’ll notice the change takes place on page load.

If you want to change the CSS styles dynamically you’ll have to attach this portion of code to some event.

For example, if you want to change the styles of your element when clicking on a button, then you have to first listen to the click event and attach a function containing the previous code.

const button = document.querySelector('button');
button.addEventListener('click', () =>
const element = document.querySelector('.demo');
element.style.backgroundColor = 'red';
>);

Note that when you apply specific styles using JavaScript, these styles have precedence over the styles applied externally on a stylesheet and even to the ones applied inline, in the HTML element itself.

 
div class="demo" style="color: blue;">Demodiv>

In this case, for instance, we have an element with an inline style providing it with a yellow background.

If we now set the CSS color property to green using JavaScript, then our element will get a green color. It will overwrite the inline style and the style applied on the external CSS stylesheet.

2. Set Multiple CSS Styles At The Same Time

Imagine you have to apply, let’s say 5 or 10 styles for a single element.

You can go one by one and have something like the following:

element.style.display = 'block';
element.style.width = '100px';
element.style.backgroundColor = 'red';
element.style.border = '2px';
element.style.fontSize = '12px';
element.style.color = 'white';
element.style.margin = '20px';
element.style.paddingLeft = '10px';
element.style.paddingBottom = '10px';
element.style.lineHeight = '13px';

But perhaps you are looking for a «smarter» way to change them all at the same time without so much code repetition.

If that’s the case, then I have good news for you!

You can actually pass a string value to the cssText property to set multiple CSS styles at once.

Even better, we can use template literals kind of strings to keep them separate in different lines as you do in your stylesheets.

// Defining all our CSS styles
const myStyles = `
display: block;
width: 80%;
background-color: red;
border: 2px;
font-size: 5em;
color: white;
margin: 20px;
padding-left: 10px;
padding-bottom: 10px;
border: 2px solid black; `
;
const element = document.querySelector('.demo');

element.style.cssText = myStyles;

If you are getting into JavaScript you might want to check our list with the Best Books To Learn JavaScript or What’s The Best Way To Learn JavaScript.

2. Change CSS class in JavaScript

// Adding a CSS class name to an element
const element = document.querySelector('.demo');
element.classList.add('new-class');

In the same way, you can also remove certain classes by using classList.remove or even toggle them when using classList.toggle .

// Removing an existing class from an element
const element = document.querySelector('.demo');
element.classList.removeClass('.new-class');
// Toggling a class from an element
const element = document.querySelector('.demo');
element.classList.toggleClass('.new-class');

3. Change CSS stylesheets dynamically

Let’s say that now you do not want to add inline styles to an element or apply a class to it. Instead, you want to apply a change at the stylesheet level. Why?

There are a couple of reasons:

  1. You might want to apply the change to all elements with a certain selector. But not just to the elements present right now on the HTML, but also to all future ones that will be added dynamically later on.
  2. There might be a huge amount of elements sharing the selector you want to apply changes to. Imagine 500 elements sharing your selector, or even 1K, 5K, 10K. Having to select all those elements using JavaScript and then loop through them to change their style (or add a class) will be EXTREMELY slow.

Here’s where modifying the CSS stylesheet directly will come on handy.

You can select the stylesheets of a document by using document.styleSheets . If you know that the stylesheet you want to modify is the second one, you can get it by using document.styleSheets[2] .

Then, you would loop through all its rules and get the one you need to modify. In this case, if you want to modify the .element class, you can compare each of the rules’ selector with .element .


// Getting the stylesheet
const stylesheet = document.styleSheets[2];
let elementRules;

// looping through all its rules and getting your rule
for(let i = 0; i stylesheet.cssRules.length; i++)
if(stylesheet.cssRules[i].selectorText === '.element')
elementRules = stylesheet.cssRules[i];
>
>

// modifying the rule in the stylesheet
elementRules.style.setProperty('background', 'blue');

And here is the Codepen example that you can play with:

4. Append And Remove CSS stylesheets dynamically

In some cases, we might want to just append a whole new stylesheet or even replace an existing one.

The reason for it might be:

  1. You have a web application that supports multiple themes and allows the user to change them dynamically.
  2. You might want to package a component in a single JS file instead of having to include both files, the JS and the CSS one.

The way this works is quite simple:

  1. 1- We write the content for our new stylesheet using template literals.
  2. 2- We select the head element of the page to append our new stylesheet.
  3. 3- We create a stylesheet element using document.createElement(«style»)
  4. 4- We append our stylesheet content to the new style element by using document.createTextNode and appendChild .
const button = document.querySelector("button");

// The content of the stylesheet
const styleSheetContent = `
.demo background:red;
> `
;

// Attaching the change to a click event in a button
button.addEventListener("click", () =>
appendStyleSheet("demo", styleSheetContent);
>);

// Appends CSS content to the head of the site
function appendStyleSheet(id, content)
if (!document.querySelector("#" + id))
var head = document.head || document.getElementsByTagName("head")[0];
console.log(head);
head.appendChild(createStyleElement(id, content));
>
>

// Creates the style element
function createStyleElement(id, content)
var style = document.createElement("style");
style.type = "text/css";
style.id = id;

if (style.styleSheet)
style.styleSheet.cssText = content;
> else
style.appendChild(document.createTextNode(content));
>
return style;
>

And here is the Codepen example so you can test it by yourself and modify a few things to your needs:

5. Overwrite CSS !important style with JavaScript

We all know the rule: «Avoid using !important». But hey! Sometimes it’s really necessary or it is just out of our control.

The !important priority property makes sure that such style will be overwriting any inline declared style (written in the HTML element itself) as well as any previously declared rule that applies to your element.

So. what if we need to overwrite the style that was previously declared using !important ?

Imagine we have our element:

And the stylesheet using the !important rule like so:

.demo 
background-color: yellow !important;
>

All you have to do is apply the priority parameter on the setProperty function that JavaScript provides us:

el.style.setProperty(property, value, priority);
var el = document.querySelector('.demo');
el.style.setProperty('background-color', 'red', 'important');

Notice how when using setProperty we specify the CSS properties exactly in the same way we do in our stylesheet. Using a dash — to separate the words. ( background-color , font-size )

References:

Источник

Читайте также:  Java создать свой jar
Оцените статью