Reputation: 97
Hello I am having the following trouble. I need to change the body class depending on what page I am now. For example if I am on index page if I am on cart page ets. The class name must be a variable that I can pass to body using PHP or JS. I am very week in JS so please give me an example how can I do it? or can I do it at all?
Upvotes: 1
Views: 2179
Reputation: 40639
You can create the individual classes
for each page
like,
for index.php => index class
for cart.php => cart class
Here some code which may help you,
CSS
.cart{
/* css */
}
.index{
/* different css */
}
And in your page use the script like,
SCRIPT
<script>
//Let your url like http://example.com/index.php
urlArray=window.location.href.split('/'); // will give array
cls=urlArray[urlArray.length-1].split('.')[0];// will give index
document.body.className=cls;// add this class to your body element
</script>
Upvotes: 0
Reputation: 3286
It works without using js. if you predefine your classname in a php snippet in front of the body tag.
<?php $class="siteclass"; ?>
<body class="<?php echo $siteclass; ?>">
</body>
Upvotes: 1
Reputation: 577
<?php
switch($pageIdentifier) {
case "index":
$class = "class-index";
case "cart":
$class = "class-cart";
default:
$class = "class-index";
}
?>
in html:
<body class="<?php echo $class; ?>">
</body>
Upvotes: 3
Reputation: 2605
In PHP: printf('<body class="%s">', $className)
In jQuery: $('body').addClass(className)
In pure JS: document.getElementsByTagName('body').className = className
Upvotes: 0
Reputation: 10583
PHP echo a variable for the ID
<body id="<?php echo $anId; ?>">
Use jQuery to set the body's attribute id
$("body").attr("id", "this_is_the_is")
Upvotes: 1