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()
}
}
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.