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?
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With