I am adding an additional className to the body tag, however the className is being added multiple times… some help on how to avoid this would be very welcome!
Thanks
<html>
<head>
<style type="text/css">
.defaultText {
font-size:100%;
}
.myNewClass {
font-size:150%;
color:red;
}
</style>
<script type="text/javascript">
<!--
var state;
window.onload=function() {
obj=document.getElementsByTagName('body')[0];
state=(state==null)?' defaultText':state;
obj.className+=state;
document.getElementById('addClass').onclick=function() {
obj.className+=(obj.className==' myNewClass')?' defaultText':' myNewClass';
state=obj.className;
}
}
-->
</script>
</head>
<body class="thisClassMustStay">
<div>My text here</div><br />
<a href='#' id="addClass">toggle class</a></div>
</body>
</html>
The first time the code is run, state us undefined so it would be better to either set it to null when declaring it or change the above to:
Given that the first time it is run the expression will evaluate to true, then state will be set to
' defaultText'. Note that there is a space at the start of the string. In some browsers, this space will be removed and in others it will be kept, so much better to remove it.At this point, ‘defaultText’ will be added to the list of classes on the body element. Again there may be issues with leading spaces that are best dealt with by robust hasClass, addClass and removeClass functions (they aren’t particularly difficult to write).
With functions suggested above, this could be:
.
If you need help with has/add/removeClassname functions, just ask.