jquery - Show and hide element when URL contains certain section of text?

admin2025-01-08  3

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

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

Share Improve this question asked Jan 29, 2019 at 12:25 Michael ElliottMichael Elliott 12 silver badges3 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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; ?>
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736265814a1072.html

最新回复(0)