Hotwire Discussion

Turbo:render not firing

Hello

I’m trying to modify the HTML dom on turbo:before-render event but the event before-render is not working

I added the below code to my connect() method inside the controller and it’s not working, but the two events before it working fine “turbo:before-fetch-request” and “turbo:before-fetch-response”

connect() {
		document.addEventListener('turbo:before-fetch-request', function(e){
			if(document.querySelector('.question-box') !== null){
				document.querySelector('.question-box').classList.add('out')
			}
		})
		
		document.addEventListener('turbo:before-fetch-response', function(e){
			if(document.querySelector('.question-box') !== null){
				document.querySelector('.question-box').classList.add('in')
			}
		})

		document.addEventListener('turbo:before-render', function(e){
			console.log('test')
		})
	}

Am I missing something, any help is highly appreciated

I think by the time this controller is connected to the dom, the turbo:before-render event was fired. Maybe attaching it on the html code?

<div data-action="turbo:before-render@window->element#perform"></div>

If it’s possible, you can attach a window event listener to perform the action for you. In your application.js do this. Here is what i’ve done to hide all modals before the page renders.

document.addEventListener("turbo:before-render", function () {
  hideAllDropdowns();
});

const hideAllDropdowns = () => {
  document
    .querySelectorAll('[data-controller="dropdown"] [data-dropdown-target]')
    .forEach((el) => {
      el.classList.add("hidden");
    });
};