Question

When the link is not pointing to anywhere (href="#") my toggleClass works as it is suppose to. But as soon as I fill in the "href" with an URL it doesnt work anymore. I suspect it is because the page is refreshed? But I'm quite new to JS. If this is the problem how can I work around it? and if it's not, then what have I done wrong?

So this is my current javascript using jquery:

$(document).ready(function()
{
    $('.button').click(function()
    { 
        $('.buttonselected').removeClass('buttonselected');
        $(this).toggleClass('buttonselected'); 
    }); 
});

And this is my HTML code:

<nav>
    <ul>
        <li> 
            <a class="button" href="?page=frontpage"> HOME </a> 
        </li>
    </ul>
</nav>
  • There are more links in the list, but that is irrelevant for this question.

  • Yes, I'm using PHP include.

  • Also, how can I set a link to "toggleClass" when the page loads so that it gets that class when someone first enters the website.

  • Thank you for the help!

Was it helpful?

Solution 2

You can use event.preventDefault()

$('.button').click(function( event )
{ 
    event.preventDefault(); // default action of the event will not be triggered.

    $('.buttonselected').removeClass('buttonselected');
    $(this).toggleClass('buttonselected'); 
}); 

EDIT:

If you want to load your frontpage (as in your link) and give it a "buttonselected" class than you need to use PHP.

Something like this

if( isset($_POST['page']) ){
    $selectedPage = $_POST['page'];
}

View

<a class="button <?php echo ($selectedPage=='frontpage')?' buttonselected':'' ?>" href="?page=frontpage"> HOME </a>

OTHER TIPS

You are right. The class goes away because the page is reloaded. If you need a specific link to have a specific class when the page loads, you'll need to hard code something to that link. Either manually put the class on the link with php or distinguish it in some other way so that JavaScript can find it.

If the link that should have the class is different based on which link you clicked previously, you will have to use a cookie or the localStorage object to retain that information.

Better yet, you should try to figure out a way to pass this information around that doesn't involve reloading the page. That would be ideal as, in most cases, users don't like to have a page reload on them when they're not expecting it.

EDIT:

The answer by @pszaba is great if you don't need to utilize query string variables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top