Using jQuery to add a link to a group 'badge'


(Bart) #1

Hi,

I’m using CSS to display a user group next to user names in topics, like here:

Now I’d like to also add a link to it. A bit of jQuery will do the trick, but I understand it won’t fire upon each page change as Discourse doesn’t always do a full page refresh:

<script>
    
$(document).ready(function(){
    $('.Editors').each(function() {
        $(this).append('<span class="staff"><a href="#">Staff</a></span>');
    });
});
   
</script>

The above script will not fire when navigating from one page to another, but it does work when you fully reload the page.

I’ve been reading up here on the forum and it seems I’d need the Discourse.Route.reopen event to trigger this script:

<script type="text/javascript">

    Discourse.Route.reopen({
        activate: function() {
            this._super();
            Em.run.next(function(){

                $('.Editors').each(function() {
                     $(this).append('<span class="staff"><a href="#">Staff</a></span>');
                });
              
            });
        } 
    });
</script>

It doesn’t do what I expect though:

  • When navigating from one page to the next, the script still doesn’t fire.
  • When reloading a page, the script fires multiple times, adding multiple badges and links.

I’m a bit lost - can someone put me on the right path?


How do you force a script to refire on every page load in Discourse?
(Régis Hanol) #2

We recently refactored our topic views to use virtual-dom. I don’t think you should use ember now. @eviltrout will confirm.

Anyway, more info about the virtual dom here


How do you force a script to refire on every page load in Discourse?
(Jeff Atwood) #3

The group should already be linked there, if it is the primary group for the user. At least that’s how it was supposed to work…


(Bart) #4

Thanks for your reply @codinghorror. I’ve tested, but adding a user to a primary group does not add a link.

Then again, I’m not sure if would help me do what I want to do as I need the link to point to a specific page that I’d like to control. A simple hack for me would be to just use the bit of jQuery to add that badge and link, if I could only get it to run reliably every time the page updates.

@zogstrip diving into your link now, thanks! update: I don’t think this is the solution for me as we’re not on the most recent Discourse version (we’re hosting with DiscourseHosting.com).


(Jeff Atwood) #5

Hmm yeah it’s going to be difficult to help on an older version of Discourse. You might need to wait until they adopt the 1.5 release, which is supposed to release at the end of this month – perhaps ask them when they think 1.5 will be adopted if it is released as planned March 30/31st.