Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add css to page via javascript

Tags:

javascript

css

I'm making a widget that will be added to external websites, and I have made a page that generates css for them to style it (text color, background color, font size, etc). I end up with a textarea filled with css for them to copy/paste to their website.

Is there a way to add this css to the current page in order to have a live preview?

like image 216
John Smith Avatar asked Jan 31 '11 03:01

John Smith


People also ask

How do I load CSS and JS dynamically?

Load CSS and JS files dynamically: We create a script element for the JS file and link element for the CSS file as required using DOM, assign the appropriate attributes to them, and then add the element to the desired location within the document tree using the element. append() method.

Can you dynamically create CSS inside a HTML page how?

With the $. ajax() method, you can load the CSS from the server and enclose the content within the <style> tags, and finally append it at the end of the <head> element of the current document. The following code demonstrates this by dynamically loading the bootstrap library.

How do you dynamically change CSS?

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.

Can we apply CSS in JavaScript?

Like we saw in the introduction, we have two ways to alter the style of an element using JavaScript. One way is by setting a CSS property directly on the element. The other way is by adding or removing class values from an element which may result in certain style rules getting applied or ignored.


1 Answers

If you want to add CSS as text

var style = document.createElement('style'); style.innerHTML = 'content'; document.head.appendChild(style); 

If you want to add a CSS file

var link = document.createElement('link'); link.setAttribute('rel', 'stylesheet'); link.setAttribute('href', 'css/my.css'); document.head.appendChild(link); 
like image 51
vogdb Avatar answered Sep 30 '22 19:09

vogdb