Executing js after DOM loaded

Hi,

I would like to run a script that appends HTML code to a specific element within the HTML’s body on page change. However, this is not working. It only works after refreshing the page.

After doing some research, I believe it is due to the script being executed after the page has changed (I currently use “api.onPageChange(() =>{}” to handle this) but BEFORE the DOM has fully loaded. As the DOM has not fully loaded, my script is unable to find the specific element to append the HTML code to.

Could any experts here provide me with some tips or work-around? :grin:

Marina

What is the element that you are trying to append the HTML to?

3 Likes

Hi Simon,

I was actually trying to add a button to the topic pages, to be specific, .title-wrapper under #topic-title.

Thankfully, I have since found a work-around to this in another thread on meta.discourse. This approach allows the editing of specific posts in topics via the api method ‘addPostTransformCallback’. I’ve shared it below to help any others who face a similar issue.

A drawback of this though, is that it only works if u navigate to the topic page from another page within the forum. If I were to refresh the page, the edit (in my case, the button) does not show up. I am currently trying to solve that, and will share if I find a solution!

What function does your button need to have? You should be able to use a plugin outlet:

https://github.com/discourse/discourse/blob/acd1693dac1bff6ff50250d942134bc48a27ff14/app/assets/javascripts/discourse/templates/components/topic-title.hbs#L5

Check out this section in @Johani’s awesome guide for more on how to make use of them. Depending on the complexity of your button, you may need to use a widget.

6 Likes

Hi tshenry!

Thanks for sharing Johani’s awesome guide. I have taken a look at it, and it seems to certainly be able to help in my situation. My button would simply crawl for specific information in topic posts, and send that information to another site.

I have one question though, if I am using a Discourse hosted instance, would I still be able to use plugin outlets? Correct me if I am wrong, but it seems to me that this is not possible, as I would not be able to edit template files.

1 Like

You can pretty much do whatever you like in a theme on a hosted install. Modifying templates or adding elements via plugin-outlets can be done in a theme. So the answer is yes!

5 Likes

Thats great! Thanks @Johani & @tshenry. Ill be marking tshenry’s reply as the answer to this problem :grin:

Cheers

3 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.