How to use jQuery hide function in my Rails application? - javascript

How to use to jquery hide api in my rails application with the following block of code .. especially for the close button...
<div class="loginwrapperinner">
<div class="widgettitle">
<button type="button" class="close" data-dismiss="alert">×</button>
<%= "<div class=\"flash_error\">#{h alert}</div>".html_safe unless alert.blank? %>
<%= "<div class=\"flash_notice\">#{h notice}</div>".html_safe unless notice.blank? %>
</div>
.....
</div>

Cleaner version:
HTML
<div class="loginwrapperinner">
<div class="widgettitle">
<button type="button" class="close" data-dismiss="alert">×</button>
<!-- empty container will not appear (try to not using html_safe!) -->
<div class="flash_error"><%= h(alert || '') %></div>
<div class="flash_notice"><%= h(notice || '') %></div>
</div>
.....
</div>
Javascript
$('.close').
siblings('.flash_error, .flash_notice').hide().
prevObject.parent().hide();

A brief explanation may change the way you've thought of this problem:
rails is generating html via the view. It is never (should never be) responsible for javascript.
Inside of your javascript file(s) is where you'll write functionality like this.
So, lets say your view has generated a message box and that box's close button had a class of box_close_button, you could simply go into your JS file and attach a listener to that class:
$('.box_close_button').doSomeJavascriptHere(function() { //whatever you want. })
So, now its not a matter what to do in rails, but rather, whats the proper jquery selectors to do what you want

I found the following solution for my problem.
$(function(){
$('.close').click(function(){
$(this).parent().hide();
});
});

Related

Bootstrap $('#myModal').modal('show') is not working

I'm not sure why but all the modal functions are not working with me.
I checked the version and the load they are fine.
I keep getting this error message:
Uncaught TypeError: $(...).modal is not a function
for the hide I already found an alternative.
instead of:
$('#myModal').modal('hide');
I used this :
$('#myModal .close').click();
And it works perfectly.
The problem now is with the show
$('#myModal').modal("show");
I also tried both
$('#myModal').modal("toggle");
And:
$('#myModal').modal();
but unfortunately none of them is working.
Here html code -when the button is clicked I will do some verification and handle a json data from the web service if it succeed then I want show my modal- everything is working except the show.
<button type="button" id="creatNewAcount" class="btn btn-default" data-toggle="modal">Sign up</button>
if there's any alternative I would like to know it.
Most common reason for such problems are
1.If you have defined the jquery library more than once.
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="modal fade" id="myModal" aria-hidden="true">
...
...
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
The bootstrap library gets applied to the first jquery library but when you reload the jquery library, the original bootstrap load is lost(Modal function is in bootstrap).
2.Please wrap your JavaScript code inside
$(document).ready(function(){});
3.Please check if the id of the modal is same
as the one you have defined for the component(Also check for duplication's of same id ).
<div class="modal fade" id="myModal" aria-hidden="true">
...
...
</div>
Note: Remove fade class from the div and enjoy it should be worked
This can happen for a few reasons:
You forgot to include Jquery library in the document
You included the Jquery library more than once in the document
You forgot to include bootstrap.js library in the document
The versions of your Javascript and Bootstrap does not match. Refer bootstrap documentation to make sure the versions are matching
The modal <div> is missing the modal class
The id of the modal <div> is incorrect. (eg: you wrongly prepended # in the id of the <div>)
# sign is missing in the Jquery selector
I got same issue while working with Modal Popup Bootstrap , I used Id and trigger click event for showing and hidding modal popup instead of $("#Id").modal('show') and $("#id").modal('hide'),
`
<button type="button" id="btnPurchaseClose" class="close" data dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span></button>
<a class="btn btn-default" id="btnOpenPurchasePopup" data-toggle="modal" data target="#newPurchasePopup">Select</a>
$('#btnPurchaseClose').trigger('click');// for close popup
$('#btnOpenPurchase').trigger('click');`// for open popup
My root cause was that I forgot to add the # before the id name. Lame but true.
From
$('scheduleModal').modal('show');
To
$('#scheduleModal').modal('show');
For your reference, the code sequence that works for me is
<script>
function scheduleRequest() {
$('#scheduleModal').modal('show');
}
</script>
<script src="<c:url value="/resources/bootstrap/js/bootstrap.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/fastclick/fastclick.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/slimScroll/jquery.slimscroll.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/datatables/jquery.dataTables.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/datatables/dataTables.bootstrap.min.js"/>">
</script>
<script src="<c:url value="/resources/dist/js/demo.js"/>">
</script>
Use .modal({show:true}) and .modal({show:false}) instead of ('show') and ('hide') ... it seems to be bootstrap / jquery version combination dependent. Hope it helps.
the solution of 'bootstrap modal is not opening' is, put your Jquery CDN first in the head tag (after starting head tag).
I wasted two days in finding this problem.
Please,
try and check if the triggering button has attribute type="button".
Working example:
<button type="button" id="trigger" style="visibility:visible;" onclick="modal_btn_click()">Trigger Modal Click</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>This is a small modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script >
function modal_btn_click() {
$('#myModal').modal({ show: true });
}
</script>
Try This without paramater
$('#myModal').modal();
it should be worked
are you sure that the id of the modal is "myModal"? if not then the call will not trigger it.
also - just from reading your post - you are triggering a function / validation with this button
<button type="button" id="creatNewAcount" class="btn btn-default" data-toggle="modal">Sign up</button>
and then if all is well - you want to trigger the modal. - if this is hte case - then you should remove the toggle from this button click. I presume you have an event handler tied to this click? you need the .modal("show") as a part of that function. not toggled from this button. also - is this id correct "creatNewAcount" as opposed to this spelling "createNewAccount"
<button type="button" id="creatNewAcount" class="btn btn-default" >Sign up</button>
use the object to call...
<a href="#" onclick='$("#myModal").modal("show");'>Try This</a>
or if you using ajax to show that modal after get result, this is work for me...
$.ajax({ url: "YourUrl",
type: "POST", data: "x=1&y=2&z=3",
cache: false, success: function(result){
// Your Function here
$("#myModal").modal("show");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
the first googleapis script is not working now a days use this second scripe given by jquery
jQuery lib has to be loaded first. In my case, i was loading bootstrap lib first, also tried tag with target and firing a click trigger. But the main issue was - jquery has to be loaded first.
Please also make sure that the modal div is nested inside your <body> element.
After trying everything on the web for my issue, I needed to add in a small delay to the script before trying to load the box.
Even though I had put the line to load the box on the last possible line in the entire script. I just put a 500ms delay on it using
setTimeout(() => { $('#modalID').modal('show'); }, 500);
Hope that helps someone in the future. 100% agree it's prob because I don't understand the flow of my scripts and load order. But this is the way I got around it
In my case, bootstrap.css and bootstrap.js versions are mismatched.
It is working if I remove the fade class. But the background is disappeared.
I added the same version of bootstrap files. Now it is working perfectly.
Thank you #Mohammed Shareef C.
Another use case that may be the cuplrit
My problem was that I had a jquery selector that was using a variable that was not assigned immediately.
My modal had a dynamic ID
<div class="modal fade" id="{{scope.modalId}}"... >
This is in angularJS, so the valud of scope.modalID wasn't being bound until $scope.onInit
vm.$onInit = function () {
$( `#${vm.modalId}` ).on('shown.bs.modal', function(){
console.log('WORKS')
});
zzz
Make sure your script tag is closed with another script tag like below
before
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"/>
After
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Django template jquery does not work

I have a django template as follows ..
...
<div class="row">
<div class="col-lg-12">
<button type="submit" class="btn btn-primary" id="related"}>KIRK</button>
</div>
</div>
...
And a script in the same template
<script>
$(document).ready( function() {
$("#related").click( function(event) {
alert("You clicked the button using JQuery!");
});
});
</script>
On button click I want to show an alert, however, this does not seem to work for me ? I cannot figure out what I am doing wrong ? Is it the way the script is defined or am not using the right selector ?
Change your html to look like this:
<div class="row">
<div class="col-lg-12">
<button type="submit" class="btn btn-primary" id="related">KIRK</button>
</div>
</div>
(remove the } )
Use whatever debugger/javascript console you prefer (I use Firebug, but you can do it with the Firefox and Chrome built-in consoles as well, I don't know about IE developer tools, which suck):
Verify that you load jQuery (and not just some javascript file of your own named jquery.js)
Verify that jQuery is loaded, and that you have one and only one node in the DOM with the id related by typing $('#related')`.
Verify that your .click line is executed after jQuery is loaded.
Try using a version of Firefox that isn't years old. I'm using 38.0, and you're using 10.0? That was released in 2013.

How to hide Bootstrap modal with javascript?

I've read the posts here, the Bootstrap site, and Googled like mad - but can't find what I'm sure is an easy answer...
I have a Bootstrap modal that I open from a link_to helper like this:
<%= link_to "New Contact", new_contact_path, {remote: true, 'data-toggle' => 'modal', 'data-target' => "#myModal", class: "btn btn-primary"} %>
In my ContactsController.create action, I have code that creates Contact then passes off to create.js.erb. In create.js.erb, I have some error handling code (a mix of ruby and javascript). If everything goes well, I want to close the modal.
This is where I'm having trouble. I can't seem to dismiss the modal when all goes well.
I've tried $('#myModal').modal('hide'); and this has no effect. I've also tried $('#myModal').hide(); which causes the modal to dismiss but leaves the backdrop.
Any guidance on how to close the modal and/or dismiss the backdrop from within create.js.erb?
Edit
Here's the markup for myModal:
<div class="modal hide" id="myModal" >
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Add Contact</h3>
<div id="errors_notification">
</div>
</div>
<div class="modal-body">
<%= form_for :contact, url: contacts_path, remote: true do |f| %>
<%= f.text_field :first_name, placeholder: "first name" %>
<%= f.text_field :last_name, placeholder: "last name" %>
<br>
<%= f.submit "Save", name: 'save', class: "btn btn-primary" %>
<a class="close btn" data-dismiss="modal">Cancel</a>
<% end %>
</div>
<div class="modal-footer">
</div>
</div>
With the modal open in the browser window, use the browser's console to try
$('#myModal').modal('hide');
If it works (and the modal closes) then you know that your close Javascript is not being sent from the server to the browser correctly.
If it doesn't work then you need to investigate further on the client what is happening. Eg make sure that there aren't two elements with the same id. Eg does it work the first time after page load but not the second time?
Browser's console: firebug for firefox, the debugging console for Chrome or Safari, etc.
to close bootstrap modal you can pass 'hide' as option to modal method as follow
$('#modal').modal('hide');
Please take a look at working fiddle here
bootstrap also provide events that you can hook into modal functionality, like if you want to fire a event when the modal has finished being hidden from the user you can use hidden.bs.modal event you can read more about modal methods and events here in Documentation
If non of the above method work, give a id to your close button and trigger click on close button.
The Best form to hide and show a modal with bootstrap it's
// SHOW
$('#ModalForm').modal('show');
// HIDE
$('#ModalForm').modal('hide');
I use Bootstrap 3.4
For me this does not work
$('#myModal').modal('hide')
In desperation,I did this:
$('#myModal').hide();
$('.modal-backdrop').hide();
Maybe it's not elegant, but it works
I was experiencing with that same error and this line of code really helps me.
$("[data-dismiss=modal]").trigger({ type: "click" });
I found the correct solution you can use this code
$('.close').click();
$('#modal').modal('hide');
//hide the modal
$('body').removeClass('modal-open');
//modal-open class is added on body so it has to be removed
$('.modal-backdrop').remove();
//need to remove div with modal-backdrop class
I ran into what I believe was a similar issue. The $('#myModal').modal('hide'); is likely running through that function and hits the line
if (!this.isShown || e.isDefaultPrevented()) return
The issue is that the value isShown may be undefined even if the modal is displayed and the value should be true. I've modified the bootstrap code slightly to the following
if (!(typeof this.isShown == 'undefined') && (!this.isShown || e.isDefaultPrevented())) return
This seemed to resolve the issue for the most part. If the backdrop still remains you could always add a call to manually remove it after the hide call $('.modal-backdrop').remove();. Not ideal at all but does work.
(Referring to Bootstrap 3), To hide the modal use: $('#modal').modal('hide'). But the reason the backdrop hung around (for me) was because I was destroying the DOM for the modal before 'hide' finished.
To resolve this, I chained the hidden event with the DOM removal. In my case: this.render()
var $modal = $('#modal');
//when hidden
$modal.on('hidden.bs.modal', function(e) {
return this.render(); //DOM destroyer
});
$modal.modal('hide'); //start hiding
I had better luck making the call after the "shown" callback occurred:
$('#myModal').on('shown', function () {
$('#myModal').modal('hide');
})
This ensured the modal was done loading before the hide() call was made.
What we found was that there was just a slight delay between the call to our server code and the return to the success call back. If we wrapped the call to the server in the $("#myModal").on('hidden.bs.modal', function (e) handler and then called the $("#myModal").modal("hide"); method, the browser would hide the modal and then invoke the server side code.
Again, not elegant but functional.
function myFunc(){
$("#myModal").on('hidden.bs.modal', function (e) {
// Invoke your server side code here.
});
$("#myModal").modal("hide");
};
As you can see, when myFunc is invoked, it will hide the modal and then invoke the server side code.
Hiding modal backdrop works but then any subsequent opening of the modal and the backdrop doesn't hide like it should. I found this works consistently:
// SHOW
$('#myModal').modal('show')
$('.modal-backdrop').show();
// HIDE
$('#myModal').modal('hide');
$('.modal-backdrop').hide();
I used this simple code:
$("#MyModal .close").click();
I was experiencing the same problem, and after a bit of experimentation I found a solution. In my click handler, I needed to stop the event from bubbling up, like so:
$("a.close").on("click", function(e){
$("#modal").modal("hide");
e.stopPropagation();
});
Here is the doc:
http://getbootstrap.com/javascript/#modals-methods
Here is the method:
$('#myModal').modal('hide')
If you need to open several times the modal with different content, I suggest to add (in you main js):
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
So you will clean the content for the next opening and avoid a kind of caching
$('.modal-backdrop').hide(); // for black background
$('body').removeClass('modal-open'); // For scroll run
$('#modal').modal('hide');
$('#modal').modal('hide'); and its variants did not work for me unless I had data-dismiss="modal" as an attribute on the Cancel button. Like you, my needs were to possibly close / possibly-not close based on some additional logic so clicking a link with data-dismiss="modal" outright would not do. I ended up having a hidden button with data-dismiss="modal" that I could programmatically invoke the click handler from, so
<a id="hidden-cancel" class="hide" data-dismiss="modal"></a>
<a class="close btn">Cancel</a>
and then inside the click handlers for cancel when you need to close the modal you can have
$('#hidden-cancel').click();
Even I have the same kind of issues. This helped me a lot
$("[data-dismiss=modal]").trigger({ type: "click" });
We need to take care of event bubbling. Need to add one line of code
$("#savechanges").on("click", function (e) {
$("#userModal").modal("hide");
e.stopPropagation(); //This line would take care of it
});
I realize this is an old question, but I found that none of these were really what I was looking for exactly. It seems to be caused by trying to close the modal before it's finished showing.
My solution was based on #schoonie23's answer but I had to change a few things.
First, I declared a global variable at the top of my script:
<script>
var closeModal = false;
...Other Code...
Then in my modal code:
$('#myModal').on('show.bs.modal', function (event) {
...Some Code...
if (someReasonToHideModal) {
closeModal = true;
return;
}
...Other Code...
Then this: (Note the name 'shown.bs.modal' indicating that the modal has shown completely as opposed to 'show' that triggers when the show event is called. (I originally tried just 'shown' but it did not work.)
$('#myModal').on('shown.bs.modal', function (event) {
if (closeEditModal) {
$('#myModal').modal('hide');
closeModal = false;
}
});
Hope this saves someone the extra research some day. I spent a bit looking for a solution before I came up with this.
In my case I was apparently trying to close the dialog too fast after showing it. So in my close modal function I used this:
setTimeout(() => {
$('#loadingModal').modal('hide');
}, 300);
document.getElementById('closeButton').click(); // add a data-dismiss="modal" attribute to an element in the modal and give it this id
I used this code -
Hide modal with smooth effect using Fade Out.
$('#myModal').fadeOut();
$('.modal-backdrop').fadeOut();
$('.modal-open').css({'overflow': 'visible'});
If you're using the close class in your modals, the following will work. Depending on your use case, I generally recommend filtering to only the visible modal if there are more than one modals with the close class.
$('.close:visible').click();
I was facing a similar problem where my custom modal would show via js but I could not hide it (there was no close button).
For me the solution was to add the content into a modal-dialog.
<div class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="loading">
<div class="modal-dialog">
loading
</div>
</div>
Without the modal-dialog it would happily show the modal, but it was impossible to hide it without the manual solutions in some of the answers here, some of which prevent you then being able to show the modal again.
This is the bad practice but you can use this technique to close modal by calling close button in javascript.
This will close modal after 3 seconds.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
window.onload=function()
{
setInterval(function(){
$("#closemodal").click();
}, 3000);
}
</script>
</head>
<body>
<div class="container">
<h2>Modal Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="closemodal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Some times
$('#myModal').modal('hide');
$('#myModal').hide();
does not get the job done so you need to add this to footer of your modal:
<button type="button" id="close_cred_modal" class="btn btn-secondary" data-dismiss="modal">Close</button>
and than add this line to close the modal
$('#close_cred_modal').click();

Many different popups needed; Is it better to use one abstracted popup to handle every scenario

I have 3 different types of modal windows to handle different events. They popup to handle either:
1) Warnings, i.e. "hey, if you leave the page you will lose your work" kind of messages.
2) Dynamic data from a form the user previously filled out, i.e. "you are about to create a page with DataX: Data X, DataY: DataY, Date: March 28, 2012.
3) Form for the user to fill out.
I was originally trying to handle all 3 of the above scenarios with one set of html/css/javascript, just passing in data and modifying divs depending on situation. As I have expanded things, i'm noticing things being harder to maintain cleanly without being sloppy about it. I have a few questions which i'll list after I walk through how things are now.
Simplified HTML for modal popups:
<div id ="popup" style="display:none;">
<div class="modal-container">
<div class="modal">
<div class="modal-header">
<a class="close" href="# " title="Press Esc to close"><div id="close-label" title="Press Esc to close">Close</div></a>
<span id="top-header">WARNING</span>
</div>
<div class="modal-body">
<div class="modal-subhead">
<img class="subhead-icon" border="0" src="">
<span id= "header">WARNING</span>
</div>
<div class="modal-message"><span>If you leave this page, you will lose unsaved changed.</span></div>
<div class="modal-input-first">
<div class="modal-label"></div>
<div id="modal-input"></div>
</div>
<div class="modal-input-second">
<div class="modal-label"></div>
<div id="modal-input"></div>
</div>
<div class="modal-footer">
<a class="secondary" href="#">Cancel</a>
<span id = "button-secondary-label">or</span>
<span class="btn_container">
<span class="btn_left"></span>
<span class="btn_center">Continue</span>
<span class="btn_right"></span>
</span>
</div>
</div>
Right now this is located in a separate file with it's css and javascript and is loaded when the page is loaded.
In the main file I am changing the popup depending on what triggered the popup, just using jquery as such:
$('.modal-message').html('New Message');
$('.modal-subhead #header').text('New header');
The dynamic data is filled in similarly after first making the ajax request to get the data.
As I said, as things grow, i'm having to change a lot of this, and it's starting to feel sloppy. Especially as i'm having to make pixel perfect changes to the css for individual elements. Would it be best to have 3 completely separate sets of html to handle these? Where is the best place for this to live, is the separate file approach?
Is it better to keep adding separate elements as I need specific ones for certain instances, like so:
<div class="modal-input-specific-thing">
<div class="modal-label"></div>
<div id="modal-input"></div>
<div id="modal-input-2"></div>
</div>
Or to use jquery to change the structure of the html on the fly?
var new_input = 'modal-input' + count;
$('#modal-input').attr('id', new_input);
Is there a better method for pushing only the elements needed to a popup like this?
If I had 10-12 scenarios, which is possible as I keep expanding this. Is there a big enough performance hit to parsing 12 different sets of html/css every time page is loaded vs doing what i'm trying to do now...Making a generic/abstracted popup window, and push elements/data to it as the user needs?
Thanks!
I should do this with jQuery and jQuery UI. The jQuery UI has a real nice popup function called dialog. ( http://jqueryui.com/demos/dialog/ )
A working version that reconstruct your situation you will see here. ( http://jsfiddle.net/7GVmz/ )
There are a lot of options you can add so as buttons, callbacks on opening and closing. You can read all of it in the documentation on the jqueryui website ( http://jqueryui.com/demos/dialog/#option-disabled )
Html
<div id="popup-1" title="popup-1">
Hello World
</div>
<div id="popup-2" title="popup-2">
Hello World
</div>
<div id="popup-3" title="popup-3">
Hello World
</div>
JS
$(document).ready(function() {
$('#popup-1').dialog();
$('#popup-2').dialog();
$('#popup-3').dialog();
});​
Note
Its important that you load the jquery library and the jquery ui library.
​
I use SweetAlert for all my JavaScript alerts, it's a Better JavaScript Popup Box than the default and is really simple to use.
swal({<br>
title: "Are you sure you want to leave?",<br>
text: "You have unsaved changes!",<br>
type: "warning",<br>
showCancelButton: true,<br>
confirmButtonClass: "btn-danger",<br>
confirmButtonText: "Yes, Exit!",<br>
closeOnConfirm: false<br>
},<br>
function(){<br>
swal("Deleted!", "Your imaginary file has been deleted.", "success");<br>
});<br>
A full tutorial is here - https://kodesmart.com/kode/javascript-replacement-alert-box

In a Rails application, where should my Javascript be and how do I call it?

Just another Rails newbie with a problem.
I have some Javascript (dynamic) in a partial .html.erb, but I have been informed in another post that this is really not where the Javascript should go. It's dynamic so I can find the correct ID of an element and only apply the javascript on that particular element. I assume it is possible to parameterise the javascript and put it in an external file and somehow call it from my partial. Would that be the correct way to do it? If so how would I do that? If not what should I do?
I have a nested resource. On the parent resource's show I am using AJAX to add children without leaving this page. I have quite a lot of Javascript magic that needs to be executed for each added child.
Partial _care_point.html.erb
<script>
$(function() {
$("#<%="node_#{care_point.id}" %>").live('dblclick', function(){
console.log('moo');
jQuery(this).hide();
jQuery('.close', jQuery(this).parent()).show();
jQuery('.node_input', jQuery(this).parent()).show();
});
});
</script>
<div id=<%="care_point.#{care_point.id}" %> class='draggable node_chin'>
<div id=<%="node_#{care_point.id}" %> class='node'><%= care_point.body %>
</div>
<textarea class='node_input'><%= care_point.body %></textarea>
<a class='close' href='#'>Close</a>
</div>
Thanks,
Erik
In your partial:
<div id=<%="care_point.#{care_point.id}" %> class='draggable node_chin care_point'>
<div id=<%="node_#{care_point.id}" %> class='node'><%= care_point.body %>
</div>
<textarea class='node_input'><%= care_point.body %></textarea>
<a class='close' href='#'>Close</a>
</div>
In public/javascripts/application.js (where your js should be)
$(function() {
$(".care_point").live('dblclick', function(){
console.log('moo');
jQuery(this).hide();
jQuery('.close, .node_input', jQuery(this).parent()).show();
});
});
Having used rails for a few years, I have never had to generate JS dynamically in the view. I can't think of a good use case that would require this (if you can think of one, leave a comment please).
I've had similar cases where I need to reference the DOM element by ID (for example, a custom library that expects an ID as a parameter). What I normally do in these cases is generate inline javascript as Erik points out, or a more hybrid solution is adding a class, then cycle through all elements of that class, get their IDs, and bind them to the respective event (or do whatever you need with the ID).
I'd also like to see a best practice for this…

Categories

Resources