John Anderson
John Anderson

Reputation: 1085

Unable to permanently change selector with jquery due to page refresh

I have a list of links to pages on my site. I want the links to change how they look (become bold) when the user clicks on them. I have set a default value for the "Home" link so when a user first goes to the website the "home" link is bold. The problem is, whenever another link is clicked I can see that it changes very briefly to bold, but then defaults back to the "Home" link being bold, since that is the default value that is hard-coded in to the website. How can I change this so that the link that is made bold is the link of the page the user is currently on (not always defaulting back to the "Home" link being bold)? Thanks so much for any assistance!

Here is the html:

<table class="sidebar_table">
    <tr class="option">
        <td class="select selected">image</td>
        <td><a href="my_website_link">A Link</a></td>
    </tr>
</table>

Here is the jquery code I'm using:

$('tr.option').click(function () {
$('tr.option td.select').removeClass('selected');
$(this).find('td.select').addClass('selected');
});

Upvotes: 0

Views: 104

Answers (2)

Erick Hoppe
Erick Hoppe

Reputation: 31

How about...

HTML

<table class="sidebar_table">
    <tr class="option">
        <td class="select page1">image</td>
        <td><a href="my_website_link.html#page1">A Link</a></td>
        <td class="select page2">image</td>
        <td><a href="my_website_anotherlink.html#page2">A Link</a></td>
    </tr>
</table>

script

...
var page = window.location.hash;

$('.option').find('a').each(
    function (i, el) {
        if ($(el).hasClass('page')) {
            $(el).addClass('selected');
        }
    };
);
...

...or use php or local storage.

edit: OK, I just realized this is very similar to what circusdei suggested. Then OP says "links are dynamically generated" Well, most pages are dynamically generated, right? So how about dynamically plugging some keyword into the link's hash, the td's class, and the script?

Upvotes: 1

circusdei
circusdei

Reputation: 1967

Option 1) You could detect which page the user is on with php, and write the classes that way.

Option 2) If you don't want to use PHP, you can use a document ready call to add the class when the page loads:

$(document).ready(function(){
    $('.sidebar_table .option .my_website_link').each(function(){
        // logic for adding the class to the page the user is on
        if(XXXXXXXXX){
             $(this).addClass('selected');
        }
    });
});

Upvotes: 1

Related Questions