I've got the following piece of code
$_helper = Mage::registry('current_category');
$_categoryUrl = $_helper->getUrlKey();
$_categoryId = $_helper->getId();
$_subcategories = $_helper->getChildrenCategories();
echo '<script>';
echo 'var el = $(document.getElementById("'.$_categoryId.'"));';
echo 'el.classList.add("active");';
echo '</script>';
$_categories = Mage::helper('catalog/category')->getStoreCategories();
foreach($_categories as $_category) {
$_subcategories = $_category->getChildrenCategories();
foreach($_subcategories as $_subcategory){
echo '<script>';
echo 'var el = $(document.getElementById("'.$_subcategory->getParentCategory()->getId().'"));';
echo 'el.classList.add("active");';
echo '</script>';
}
}
What it does is to look for categories and their subcategories, in order to apply a script. The result is that the script -in the first part- is applied to the current category without checking if this is is a parent category or a child category. In the second part, the script gets applied to all subcategories which is not want I'd want.
I just want that Magento identifies the current category and then make a check:
If the current category is a parent category, then the script should apply the script only to it, adding the class 'active' to the element of that category.
If the current category is a child category, then the script should be applied only to that subcategory, adding the class 'active' to the element of its parent category.
Code so far (v2):
<?php
/** @var \Mage_Catalog_Model_Category $category */
$category = Mage::registry('current_category');
$isChild = $category->getLevel() > 2;
$isParent = (bool)$category->getChildrenCategories()->getSize();
$categoryId = null;
if($isChild) {
$categoryId = $category->getParentCategory()->getId();
} elseif($isParent) {
$categoryId = $category->getId();
}
?>
<?php if($categoryId): ?>
<script>
<?php
echo 'if (( “#dropdown-menu” ).is( “.active” )) { ';
echo 'var el = document.getElementById("'.$categoryId.'");';
echo 'el.classList.add("active");';
echo '}';
?>
</script>
<?php endif; ?>
The javascript does not seem to work, it is not to see in the browser's console when inspection the category page.