ext-core equiv of Ext.util.CSS.swapStyleSheet()
How would I best emulate the ExtJS swapStyleSheet() function using only ext-core.js?
Code:
var origStyle = true;
Ext.get('swapper').on('click', function(){
if (origStyle){
Ext.util.CSS.swapStyleSheet('ss', '/lib/css/sec.css');
} else {
Ext.util.CSS.swapStyleSheet('ss', '/lib/css/light.css');
}
origStyle = !origStyle;
})
Here is a fancier version
While playing around with ways to swap style sheets I had made a version that is more dynamic and more error friendly then my earlier post. I didn't post that version due to it being an overly complex solution when an easy one for your end result may have been more appropriate.
Since you are learning, seeing this code may help.
Good Luck with your project.
Sample Functions
switchCSS
Creates or swaps out a css by passing the id/element and the url for the new css file.
link: Pass a string id of the link or the element to effect. The element can be either the dom element or an Ext Element that is the link you want to swap out.
Note: If a string value is passed and no element is found, one will be created and the ID set the value of link.
newurl: The string URL of the new css file.
Code:
function switchCSS( link, newurl){
if( !newurl ){return};
var elem = link.dom || Ext.getDom(link);
if (!elem && typeof(link) !== 'object'){
//--- No link exists and we are looking for a string ID - then Add one to the header
elem = document.createElement('link');
Ext.apply( elem, {
rel: 'stylesheet',
type: 'text/css',
href: newurl
})
//--- assume if a link is passed and it does not exist, the string passed must be id
if( typeof(link) !== 'object' ){elem.id = link};
//--- Append to header - one time operation per ID
Ext.fly(document.getElementsByTagName("head")[0]).appendChild(elem);
};
//don't crash even if I pass invalid stuff
if (!elem){return};
elem.href = newurl;
}
//Sample usage
var someurl = 'demo2.css';
switchCSS( 'toswap', someurl );
//or
switchCSS( cssDom, someurl );
//or
switchCSS( cssElement, someurl );
switchCSS
Finds a css by filename and swaps it out
filename: A string that is just the filename including .css. Do not use the path.
newurl: The string URL of the new css file.
Code:
//--- Function that swaps by filename if found
function switchCSSByName( filename, newurl){
var elem;
var finder = Ext.DomQuery.select("link[href$=" + filename + "]");
if( finder.length == 1){elem = finder[0];};
if (!elem){return};
elem.href = newurl;
}
//Sample Usage
switchCSSByName( 'demo1.css','css/demo2.css' );
Since your usage fits one of the supplied patterns, you should be able to pop in the above code and use this ...
Code:
var origStyle = true;
Ext.get('swapper').on('click', function(){
if (origStyle){
switchCSS('ss', '/lib/css/sec.css');
} else {
switchCSS('ss', '/lib/css/light.css');
}
origStyle = !origStyle;
})