I have a div and need to render different .js.erb actions based on the clickevent
on that div . For example:
dblClick
, I want to render the new.js.erb click
, I want to render show.js.erb In my asset/javascripts directory I have a file.js.coffee :
$('#myDiv').on "dblclick" ->
$.getScript('/projects/xy/plan/new')
This basically works. It shows the modal in my new.js.erb :
$("#myModal").modal("show");
How can I make the $.getScript
URL dynamic and include an object for the show and edit action?
Edit: Rich Pecks answer seems to be correct. Because of simplicity I just wrote $('#myDiv').on "dblclick"
. The full example is:
$zoomcontainer = $("section").find(".parent")
$panzoom = $zoomcontainer.find(".panzoom").panzoom(
$zoomIn: $zoomcontainer.find(".zoom-in")
$zoomOut: $zoomcontainer.find(".zoom-out")
$zoomRange: $zoomcontainer.find(".zoom-range")
$reset: $zoomcontainer.find(".reset")
).on("dblclick", (e) ->
How should I put my data attributes in the HTML?
This is my basic HTML structure:
<section>
<div class="parent" data-project_id="<%= @project.id %>" data-plan_id="<%= @plan.id %>">
<input type="range" class="zoom-range" />
<div id="plan" class="panzoom" style="background: url('<%= @plan.asset.url %>') no-repeat;>
</div>
</div>
</section>
From what I can see, you could use a different event handler:
var plan_url = "/projects/xy/plan";
$('#myDiv').on "dblclick" ->
$.getScript(plan_url + '/new')
$('#myDiv').on "click" ->
$.getScript(plan_url + '/show')
Although this seems too simple to be what you're asking for
Dynamic
If you're looking to handle dynamic routes, you'll need to be able to pass the various object variables through your HTML (JS can't read Rails variables)
You'd have to do something like this:
#app/views/posts/show.html.erb
<%= content_tag :div, class: "your_class", data: {project_id: @post.project_id, plan_id: @post.plan_id} do -%>
Your div
<% end -%>
#-> <div class="your_class" data-project_id="15" data-plan_id="6">Your Div</div>
This will allow you to do this:
#app/assets/javascripts/application.js
$('#myDiv').on "dblclick" ->
project = $(this).data("project_id")
plan = $(this).data("plan_id")
$.getScript('/projects/' + project + '/plan/' + plan)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.