thegreenfrog
thegreenfrog

Reputation: 225

.addClass() not functioning properly

In one one of my spacebar calls currentCategory, I call addClass(disabled-link), which changes the color of the current category text. This works normally when I am clicking on categories on this page, which essentially just reroutes back to the same page, listing items for the clicked on category. However, when I first arrive at this page from another page, the current category text is not changed properly.

Here is my Template.template_name.helper call for this:

currentCategory: function(category) {
    check(category, String);
    //console.log(this);
    if(String(this) == Session.get('category')){
        console.log('matching category ' + category);
        $("#" + category).addClass('disabled-link');
        return true;
    }
    return false;
}

Here is the html that calls this function:

<div class="filter-list" id="category-filter">
    <h3>Filter by:</h3>
        {{#each category}}
            <div class="filter-element" id={{this}}>
            {{#if currentCategory this}}

                    <div class="accompany-icon">

                    </div>
                    {{this}}

                {{else}}
                    <a class="filter-link" href="{{pathFor 'produceListFilter' _filter=this}}">
                        <div class="accompany-icon">

                        </div>
                        {{this}}
                    </a>
            {{/if}}
            </div>
        {{/each}}


</div>

As seen above, I rely on a Session variable, but I can confirm that every time, the Session variable is set properly and does run the .addClass function, but the UI changes are not there. In case this helps, this is my css:

.disabled-link {
    color: #666666;
} 

Is there something special about rendering that prevents me from editing the DOM until it fully renders or something? Thanks for the help.

Upvotes: 1

Views: 105

Answers (1)

Jordan Davis
Jordan Davis

Reputation: 1327

A pretty high percentage of questions about meteor come down to things not being rendered in time for the javascript that is supposed to run on it. Try putting this into the Template.template_name.onRendered. I would also put it in the parent template, and run it in a tracker.afterFlush so it isn't running every time the sub-template runs.

Template.template_name.onRendered(function(){
  if (!this.rendered){ //run only on first render
    tracker.afterFlush(highlightCategory);
  }
});

function highlightCategory(){
  Session.get('category');
  $("#" + category).addClass('disabled-link');
}

Upvotes: 1

Related Questions