hotwired / turbo-rails

Use Turbo in your Ruby on Rails app
https://turbo.hotwired.dev
MIT License
2.09k stars 323 forks source link

jQuery fadeToggle with stopPropagation breaks link_to in turbo frame #378

Open gabrielboeker opened 2 years ago

gabrielboeker commented 2 years ago

While jquery implemented in a rails 7 app in application.js, ive got

$(".context-menu-trigger").on("click", function(e) {
    e.stopPropagation();
    $(this).find(".context-menu").fadeToggle(100);
});

When wrapping a turbo frame around some code that includes a .context-menu-trigger included, link_to will break the turbo frame as it would be expected with target: "_top"

When moving the link_to out of the context-menu-trigger everything works well. I figured its because of the stopPropagation() which is needed unfortunately. I also tried using

    event.preventDefault()
    event.stopImmediatePropagation()

With no success. Is this a bug or a case for stack overflow?

marcoroth commented 2 years ago

Hey @gabrielboeker, is the content of the Turbo Frame loaded asynchronously? If so, that would explain why.

The problem with jQuery is, that it's just being evaluated once on first page load. Sadly it's not re-executed if you dynamically add matching elements to the DOM, which would be case with a Turbo Frame.

The ideal solution would be to wrap your logic in a Stimulus controller, so you can control when that element gets connected and then attach the needed event-listener in the callback.

If you still decide to go the jQuery route, you probably need to re-execute your snippet in a turbo:frame-load or turbo:frame-render event listener in order to attach your logic to the newly appeared elements.

pau-not-paul commented 2 years ago

I can confirm it's a bug and it's very easy to replicate: just add onclick="event.stopPropagation();" to the \.

vishnuMohanan01 commented 6 months ago

Any updates on this ?