hotwired / turbo

The speed of a single-page web application without having to write any JavaScript
https://turbo.hotwired.dev
MIT License
6.54k stars 415 forks source link

How execute js code in rails 7 'create.turbo_stream.erb' file #1247

Closed kashifcodility closed 2 months ago

kashifcodility commented 2 months ago

here is my comment controller code

      def create
             @comment = current_user.comments.new(comment_params)
             @feed = Feed.find(params[:comment][:feed_id])
             @comment.commentable = @feed
            @parent = params[:comment][:parent] if params[:comment][:parent].present?
            respond_to do |format|
               if @comment.save
                 format.turbo_stream
                 format.html { redirect_to feeds_path, notice: "Comment was successfully created." }
                 format.json { render :show, status: :created, location: @comment }
            else
                format.html { render :new, status: :unprocessable_entity }
                format.json { render json: @comment.errors, status: :unprocessable_entity }
           end
        end
     end

my 'create.turbo_stream.erb' code is below

 <%if @parent.present?%>
     <%= turbo_stream.update("feeds-list-parent-#{@parent}",
      partial: "feeds/feed",
      locals: { feed: @feed }) %>
 <%else%>
     <%= turbo_stream.update("feeds-list-#{@feed.id}",
      partial: "feeds/feed",
      locals: { feed: @feed }) %>
 <%end%>
  console.log('hi') # this is not working here and no log. also <script> tag is not working.

How this is possible to execute some js code, beacause i want to hide pop up div using js here?

Thanks

i tried different option to execute js but not working.

afcapel commented 2 months ago

@kashifcodility Turbo doesn't provide any means to execute JS, you'll have to use Stimulus for that.

Also, Github issues are for reporting bugs, you should use the Hotwire forum to ask usage questions.

kashifcodility commented 2 months ago

ok i use

     <button type="submit" data-action="click->comment#closePopup" data-turbo="true" class="inline-flex items-center px-5 py- 2.5 text-sm font-medium text-center text-white bg-blue-700 rounded-lg focus:ring-4 focus:ring-blue-200 dark:focus:ring-blue-900 hover:bg-blue-800">
    Comment
    </button>
kashifcodility commented 2 months ago

this is also working

    <%= turbo_stream.after "feeds-list-#{@feed.id}" do %>
      <script>
        console.log("hooooi")
      </script>
   <% end %>