0

I require #nav1 to display and #nav2 to hide on all pages which include "/category-1/" in the URL.

I require #nav2 to display and #nav1 to hide on all pages which include "/category-2/" in the URL.

I have this code:

    <script>  

var url = window.location.href;

if (url.indexOf("/category-1/") > -1)
{
    document.getElementById('#nav1').style.display = 'none';
    document.getElementById('#nav2').style.display = 'true';
}

else if (url.indexOf("/category-2/") > -1)
{
    document.getElementById('#nav2').style.display = 'none';
    document.getElementById('#nav1').style.display = 'true';
}

</script>

But it appears to be having no effect.

Thanks, Michael

0

true is not a valid value for display in CSS. You either need to use one of the valid values for the display property or an empty string to remove the style override.

If both menus are styled to display by default then you'd just be better off adding and removing display: none;, rather than setting a specific value when its displayed:

if (url.indexOf("/category-1/") > -1)
{
    document.getElementById('#nav1').style.display = 'none';
    document.getElementById('#nav2').style.display = '';
}

else if (url.indexOf("/category-2/") > -1)
{
    document.getElementById('#nav2').style.display = 'none';
    document.getElementById('#nav1').style.display = '';
}

If you have control over your theme's templates though, you'd probably be better off hiding and showing the correct nav in the template. You can use is_category() to check if you're viewing a specific category archive, or has_category() to check if the current post has that category:

<?php if ( is_category( 'category-1' ) || ( is_single() && has_category( 'category-1', get_queried_object() ) ) ) : ?>
    <nav id="nav1"></nav>
<?php elseif ( is_category( 'category-2' ) || ( is_single() && has_category( 'category-2', get_queried_object() ) ) ) : ?>
    <nav id="nav2"></nav>
<?php endif; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.