Turbo:before-visit is not firing

Hello guys,

this is my first project using hotwire and stimulus JS.
I’m trying to listen to turbo:before-visit event to do some validation before executing the visit and here is my code

connect() {
	document.addEventListener("turbo:before-visit", (event) => {
		console.log("test")
		this.validateAnswer(event)
	})  
}

validateAnswer(event){
	var answer = 0
		this.radioAnswerTargets.forEach( (el, i) => {
			if(el.checked == true){
				answer =  el.value
			}
		})
		if(answer == 0){
			this.errorMessageTarget.innerText = "You have to answer the question before moving to the next one!"
			event.preventDefault()
		}
}

why is turbo:before-visit is not firing?

Thanks in advance

What does the HTML look like?

Here is the HTML code

<div data-controller="questions" data-questions-target="questionsContainer">

    <%= turbo_frame_tag "question" do %>

        <%= render partial: 'question', locals: {q: @question } %>

    <% end %>

</div>

Partial HTML code

<%= turbo_frame_tag "question" do %>

<div class="question-block question-box" >

    <h3 class="question-title"><%= q.question %></h3>

    <div class="question_answers">

        <%= render partial: "wizard/fields/#{q.qtype}", locals: {q: q} %>

    </div>
</div>
<%= link_to "Prev", wizard_previous_question_path(id: q.prev_question), id: "prev-question", data: {action: "questions#prev" } %>

<%= link_to "Next", wizard_next_question_path(id: q.next_question), id: "next-question", data: {action: "questions#next" } %>

<div data-questions-target="errorMessage"></div>

<% end %>

Thank you

turbo:before-visit fires before visiting a location, meaning when the page location (url) changes. Turbo-frames do not change the page location and does not dispatch a turbo:before-visit event.

You might try turbo:before-stream-render or a stimulus to detect mutation.

1 Like