What happens to the dom when you re-render a partial with js.erb? I can no longer get click events.
Based on this tutorial, I have followed it to re-render a js.erb partial which works fine. When I click the "cat.name" button (on linked page), and on that page is another button that I'm listening for click events but not working.
The run down:
On index page, click event works. When I make the request for from_category, no more click event. So what really happen?
Html:
<button id="test" value="ok">click</button>
JS:
$( "#test" ).on("click", function(e) {
console.log(e.target.value)
});
You click events don't bind to the new dom elements you should use event delegation to bubble the events to the newly created dom elements
$('body').on('click input keypress','.the_dynamic_element',function(){
});
No need to bind the event on body you can use this format to bind the event to the selector
$(document).on('click', '#test', function(e) {
console.log(e.target.value)
});
Related
first i created navigation click event
$('#inner-navigation li a')
.on('click', function (e) {
e.preventDefault();
AjaxNavUrl.checkURL(this.hash);
});
then it conducts ajax call and response html data
based on navigation key
$(".panel-body").html(data);
first ajax click working nicely..
then whithin that responese html data there is rest of click event and ajax call like
$(document.body).on('click', '.page-demos .page-wrapper', function (e) {
e.preventDefault();
and this
$(document.body).on('click', '.button-next', function (e) {
e.preventDefault();
but it seems like click event or e.preventDeafult() function is not working
I got the answer from jQuery doc here is what I learned,
Event Propagation
Understanding how events propagate is an important factor in being able to leverage Event Delegation. Any time one of our anchor tags is clicked, a click event is fired for that anchor, and then bubbles up the DOM tree, triggering each of its parent click event handlers:
<a>
<li>
<ul #list>
<div #container>
<body>
<html>
document root
This means that anytime you click one of our bound anchor tags, you are effectively clicking the entire document body! This is called event bubbling or event propagation.
Since we know how events bubble, we can create a delegated event:
$("#list").on("click", "a", function(event) {
event.preventDefault();
console.log($(this).text());
});
Notice how we have moved the a part from the selector to the second parameter position of the .on() method. This second, selector parameter tells the handler to listen for the specified event, and when it hears it, check to see if the triggering element for that event matches the second parameter. In this case, the triggering event is our anchor tag, which matches that parameter. Since it matches, our anonymous function will execute. We have now attached a single click event listener to our <ul> that will listen for clicks on its descendant anchors, instead of attaching an unknown number of directly bound events to the existing anchor tags only.
linkUsing the Triggering Element
What if we wanted to open the link in a new window if that link is an external one (as denoted here by beginning with "http")?
// Attach a delegated event handler
$("#list").on("click", "a", function(event) {
var elem = $(this);
if (elem.is("[href^='http']")) {
elem.attr("target", "_blank");
}
});
This simply passes the .is() method a selector to see if the href attribute of the element starts with "http". We have also removed the event.preventDefault(); statement as we want the default action to happen (which is to follow the href).
We can actually simplify our code by allowing the selector parameter of .on() do our logic for us:
// Attach a delegated event handler with a more refined selector
$("#list").on( "click", "a[href^='http']", function(event) {
$(this).attr("target", "_blank");
});
The click binding adds an event handler so that your chosen JavaScript function will be invoked when the associated DOM element is clicked. This is most commonly used with elements like button, input, and a, but actually works with any visible DOM element.
Example
<div>
You've clicked <span data-bind="text: numberOfClicks"></span> times
<button data-bind="click: incrementClickCounter">Click me</button>
</div>
<script type="text/javascript">
var viewModel = {
numberOfClicks : ko.observable(0),
incrementClickCounter : function() {
var previousCount = this.numberOfClicks();
this.numberOfClicks(previousCount + 1);
}
};
</script>
Each time you click the button, this will invoke incrementClickCounter() on the view model, which in turn changes the view model state, which causes the UI to update.
I am using google translator which creates dynamically translator bar,it has show original button (click on below image link).
I want to fire click event of "show original" button manually using javascript or jquery but is is not working, see some of the code snippets that i tried.
$("#myBtn").click(function(){
$("#\\:1\\.restore").click();
//or
$("#\\:1\\.restore").on('click');
//or
$("#\\:1\\.restore").trigger('click',jQuery.Event( "click" ));
//or
document.getElementById(':1.restore').click();
})
imageURL: http://1drv.ms/1KhfLbo
The event on myBtn is not fired and your event handler is not working.
For dynamically added elements use event delegation.
$(document).on('click', '#myBtn', function() {
// Your Code Here
});
To trigger event:
$("#\\:1\\.restore").trigger('click');
You need delegate from a container such as document
$(document).on('click', '#\\:1\\.restore', function(){...}));
I want to fire click event of "show original" button manually
Use
$('#\\:1\\.restore').trigger('click')
or
$('#\\:1\\.restore').click();//with no parameters
I got the answer.
Actually translate bar was inside iframe tag, so we need to select iframe (container) then any element inside that.
$("#myBtn").click(function(){
$('#\\:1\\.container').contents().find('#\\:1\\.restore').click();
});
I have a button being created after the DOM is created. That button has an action. What I'm having trouble is binding that action to the button. I have researched and people said to us the .on() function but it doesn't seem to be working. What am I missing?
http://jsfiddle.net/e7a4X/
HTML
<button id="firstClick">Click me to create another button</button>
<div id="container"></div>
Javascript
$('#firstClick').click(function() {
$('#container').append('<button class="second-button">Button after DOM</button>');
});
$('.second-button').on('click', function () {
alert("Success");
})
Working demoL http://jsfiddle.net/Metsx/ or http://jsfiddle.net/ZB2Ns/
API : .on http://api.jquery.com/on/
Now to make your event know about the click event you need .on at document or at #container level, which attaches event handlers to the currently selected set of elements in the jQuery object.
Rest should fit your need :)
Code
$('#firstClick').click(function() {
$('#container').append('<button class="second-button">Button after DOM</button>');
});
$(document).on('click', '.second-button', function () {
alert("Success");
})
You will need to tell the DOM, parent to listen to its child.
The issue is that Your new .second-button is a new element, and you have defined your .click function before the DOM actually exists.
But all DOM interactions will trigger a event propagations(bubbling), therefore you can tell #container to listen for click events coming from .second-button
Or use $(document).on to listen, since the bubbling will go all the way to the document root.
If you are a performance minimalist than you would just do #container .on, and stop the propagation from that point, since theres no need to travel to every parent node, but you might eventually need to listen it from the parent of the #container, who knows
I have an app where clicking a link brings up a modal. In the modal is a form. I need to monitor for that form's submission.
I'm attaching a click handler in my JS like so:
$('.vex-dialog-form :submit').click (event) ->
alert "hi"
That alert isn't firing, I believe it's because I need to attach some kind of event handler for that modal loading then put the submit event inside of that.
Any suggestions on how to go about this?
you need event delegation for dynamically added DOM. use .on():
$('.vex-dialog-form').on('click',':submit',function(){
alert("hi");
});
if parent .vex-dialog-form is also getting added dynamically, then use:
$(document).on('click','.vex-dialog-form :submit',function(){
alert("hi");
});
Try this way:
$(document).on('click', '.vex-dialog-form :submit', function(){
alert('hi');
});
In this case document is waiting for click and after it gets clicked, jQuery finds out whether your submit button is clicked or not
I have a hidden div on page which needs to be opened on click function.
The click-able link is inside the bootstrap popover so how can I get the page div opened by clicking on popover content link.
here is the Fiddle
$( "#open" ).click(function() {
$('.open-this').slideToggle("slow");
});
instead of this code:
$( "#open" ).click(function() {
$('.open-this').slideToggle("slow");
});
try this
$("body").on("click","#open",function(e) {
e.preventDefault();
$('.open-this').slideToggle("slow");
});
check out the updated fiddle http://jsfiddle.net/bfkLM/15/
The problem on your code is that the link is generated from your code and not presented in the dom when your event handler is trying to get it to attach the click event to it.
so the solution is to use Delegated events:
from the official; jquery website
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers. This
element could be the container element of a view in a
Model-View-Controller design, for example, or document if the event
handler wants to monitor all bubbling events in the document. The
document element is available in the head of the document before
loading any other HTML, so it is safe to attach events there without
waiting for the document to be ready.
that's why my new code will work because it attaches the event handler to the body tag and checks that a click event is coming from my target element (open), when this happen it will fire up my code and the popup will be displayed
one more thing, the use of e.preventDefault(); is to prevent the page from navigating to the href property of your anchor.
The event is not attached to the link, because I guess you aren't doing it after document is ready.
For testing purpose I've added onclick function to the link
onclick="$(\'.open-this\').slideToggle("slow");return false;"
and it worked.
Fiddle
Solution:
$(function(){
$( "#open" ).click(function() {
$('.open-this').slideToggle("slow");
return false;
});
});