Beruflich Dokumente
Kultur Dokumente
Soyouvegotawebpage.YouvemarkeditupwithstructuralXHTML.Youvealsobeena
goodlittlewebdeveloperandusedstylesheetstocontrolwhatyourdocumentlookslike.
Youveevengonetheextramileandcreatedseveralalternativestylesheetstoshowhow
hardcoreyouare.
Great.Butnowyouneedacrossbrowserwaytodynamicallyswitchbetweenthestyle
sheets.
PREFERRED
Thesestylesheetsareenabledbydefault(theyareonwhenthepageisloaded).They
canthenbedisablediftheuserselectsanalternatestylesheet.
Tomakeastylesheetpreferred,the attributeissettostylesheetandthestylesheet
isnamedwiththe attribute.
Severalpreferredstylesheetscanbegroupedtogetherbygivingthemidenticaltitle
attributes.Thesegroupedstylesheetsarethenallenabledanddisabledtogether.Ifmore
thanonegroupofpreferredstylesheetsaredeclared,thefirstgrouptakesprecedence.
Tomake preferred,atitleattributeisadded,givingthedefaultstyleaname.
ALTERNATE
Thesestylesheetscanbeselectedbythevisitorasalternativestothepreferredstylesheet.
Thisallowsthevisitortopersonalizeasiteandchoosehisorherfavoritescheme.They
canalsobeusedforaccessibility.
Tospecifyanalternatestylesheet,therelattributeissettoalternatestylesheetandthe
stylesheetisnamedwithatitleattribute.Aswithpreferredsheets,thesestylesheetscan
alsobegroupedtogetherbygivingthemidenticaltitleattributes.
Usingthepreviousexampleagaintomake intoanalternatestylesheet,the
keywordalternateisaddedtotherelattribute.
Notethattheserelationshipsonlyapplytoexternalstylesheetswhichareincludedusing
thelinkelement.
Swappin Styles
Whenadocumentisinitiallyloaded,thepersistentandpreferredstylesheetsareapplied
tothedocument.Thealternatestylesheetscanthenbeselectedbytheuser.TheW3Ctells
usthatthebrowsershouldgiveusachoiceofthestylesheetwewanttouse,andsuggests
thatperhapsadropdownmenuortoolbarwillbeprovided.
Sofar,sogood.Wehaveseveralstylesheetsandthevisitorcanchoosetheirfavoritefrom
amenu.Butthenweencounteraproblem.Amajorone.Mozillaprovidesamenutoselect
thestylesheetwewanttouseundertheviewmenuitem.ButMicrosoftInternetExplorer
(MSIE)providesnosuchmenu.Sowehaveseveralstylesheets,andnowaytoaccess
theminMSIE.
HereswherealittlebitofJavaScriptcanbeusedalongwiththeDOMtoprovideawayfor
MSIEandMozillauserstoselectthestylesheettheywanttouse.Theirpreferencecan
alsobestoredinacookie.AndbecauseweareusingthelinktagsastheW3Ctellsusto,
theJavaScriptdoesntinterferewiththemenuinMozilla,anditdegradesverygracefully.
The Script
Firstweneedthescripttobeabletodifferentiatebetweenthethreedifferenttypesofstyle
sheet.Thisisrelativelyeasytodo,asweonlyneedtochecktwooftheattributesofeach
linkelement.
Isitalinktoastylesheet?
Isthereatitleattribute?
Doestherelattributecontainthekeywordalternate?
Notethatwecheckforthestringaltbecausesomebrowsersacceptthekeyword
alternativeinplaceofalternate.
Usingthesethreecheckswecanwriteafunctiontoswitchstylesheets.Thisinvolves
loopingthrougheverylinkelementinthedocument,disablingallpreferredandalternate
stylesheetsthatwedontwantactive,andenablingallpreferredandalternatestylesheets
thatwedowantactive.
Notethatonlypreferredandalternatestylesheetlinkelementswillhaveatitleattribute.
Thechangefunctionlookslikethis:
COOKIES
Nowwecanchangethestylesheet.Cool.Wehaveamorepersonalizedpage.Excellent.
Butwedonthaveapersonalizedsite.Thepreferenceisonlyappliedtothecurrentpage
whenweleavethecurrentpagethepreferenceleaveswithus.Thissituation,however,can
berectifiedwithacookie.
Tostoreacookieweneedanotherfunctiontoreturnthecurrentstylesheet.Wealsoneed
twofunctionstostoreandreadthecookie.
Toreturnthecurrentstylesheetwelookforanactivepreferredoralternatestylesheet
andcheckitstitle.
Firstweloopthroughallthelinkelementsinthedocumentagain.Wethencheckwhether
thelinkisastylesheet.Ifitis,wecheckwhetherthestylesheethasatitle.Thistellsus
thatthestylesheetiseitherpreferredoralternative.
Thelastcheckistoseewhetherornotthestylesheetisactive.Ifallthreechecksreturn
true,wehavethecurrentstylesheetandwecanreturnthetitle.
Thefunctionendsuplookinglikethis:
Asthisisanarticleonstyle,andcookiesareacompletelydifferenttopic,Iwontexplain
thecookiefunctionshere,butIwillincludethemforyourconvenience(thesefunctions
arewrittenbyALAauthorPeterPaulKoch(http://www.quirksmode.org/)).
MSIEdoeshaveaproprietaryHTMLattribute,alsocalleddisabled,thatappliestolink
elements.Thisattributeisinitiallysettofalseforalllinkelements.
TosettheMSIEdisabledattributetomatchtheDOMLevel2disabledattribute,wecan
callthesetActiveStyleSheet()functionwiththenameofthepreferredstylesheet.
Tofindoutwhichstylesheetisthepreferredstylesheet,weneedanotherfunction.
Becausethisfunctionissosimilartothe functionImnot
goingtoexplainhowitworks,buthereiswhatitmaylooklike:
Intheonloadfunction,wefirstsetatitlevariable.Thiseitherholdsthevalueofthe
previousstylesheetthatisstoredinthecookie,orifthereisntone,thetitleofour
preferredstylesheet.Tokeepthingslogical,letscallthecookiestyle.
Nextwecallupthe functionpassingthetitlevariableasthe
title.Ouronloadfunctionlookssomethinglikethis:
Notethatitmaybedesirabletocallthisfunctionbeforetheonloadeventaswell,causing
thedocumenttopaintwithourstylesheetpreference.
Ifyouchoosetodothis,makesurethefunctioniscalledafterthefunctionsandthelink
elementshavebeendefined.
ONUNLOAD
Tosavethecookieintheonunloadeventissimpler.Allwehavetodoisusethe
functiontoreturntheactivestylesheet,andsavethisina
cookie.Usingthefunctiontostoreacookiewewillendupwithsomethinglikethis:
Toallowthevisitortochangetheactivestylesheet,youcouldusejavascriptonClick
events.Forexample,tohavetheoptiontoswitchbetweentwothemeswithtitlesdefault
andpaul,youcouldusethefollowingHTML:
Oncethevisitorhasselectedatheme,itwillbestoredinacookie.Tousethesametheme
throughoutyourwebsite,thesamestylesheetandjavascriptlinkelementsshouldbe
includedintheheadofeverypageofthesite.
THATS ALL, FOLKS!
Thereyouhaveit,acustomizablewebsitethatuseslinkelementstolinktostylesheetsas
theW3Chastoldusweshould.Enjoy!
Issue
126
ISSN 1534-0295 Copyright 19982015 A List Apart & Our Authors