Reputation: 623
I am using ryanb's simple_nested_form and i have the following Code
<%= f.link_to_add "Shipping Address", :shipping_addresses %>
I want this link to be executed only once and then it should hide. I believe i should use jquery or ajax but i don't know much about ajax/jquery. Can anyone suggest how i can make this Link execute only once? Thanks in advance.
Upvotes: 1
Views: 2892
Reputation: 37045
To get the link to actually fire when using the hide
method, you have to include a callback in the hide()
method to return true, which will bubble up to the original event callback. My tests with just returning true in the main function didn't work, so I think the hide
method must short-circuit any event propagation. Since you want it to fire only after they've clicked it the second time, you would want to bind the click
event twice, the first click calls the function that binds any following click events on that element to the hide
method. Basically just a second layer.
$("a").on('click', function(e) {
$(this).on('click', function() {
$(this).hide();
});
});
If you don't want the second-click to actually fire the primary event the second time (like if you have it make text display, but on second click, you don't want the text to re-display), you should unbind the primary event, like so:
$("a").on('click', function(e) {
$(this).unbind(e);
$(this).on('click', function() {
$(this).hide();
});
});
Upvotes: 1
Reputation: 9296
First of all download jQuery from www.jquery.com. Next add the JS file to your page. The next thing should be something like this:
<script type="text/javascrip>
$(document).ready(function() {
$("#your_link_id").click(function() {
$(this).hide();
});
});
</script>
That's about it. If you want to hide every anchor that is clicked replace #your_link_id with a as in $("a"). Also, if you anchor tag has some class, you can hide it based on its class, like $("a.myClass").
UPDATE:
In relation to your comment, a code might look something like this:
$(document).ready(function() {
$("a:not(.clickedOnce)").click(function() {
$(this)
.addClass("clickedOnce")
.on("click", function()
{
$(this).hide();
});
});
});
Basically, when you click on a link a class named clickedOnce will be added. After that with you use .on() to tell this link to hide itself on second click.
Hope this helps.
EDIT: Here is the sample how this works: http://jsfiddle.net/rvQ4w/23/
Upvotes: 1