Let's say I have a file called example.html that looks like this:
<button>Click me</button>
Now let's say I have another file called index.html that contains this:
$.get('example.html',function(data){
$('body').html(data);
});
How can I do this...:
$('button').click(function(){
$(this).hide();
});
...from my example.html file?
Try this:
$.get('example.html',function(data){
// load
$('body').html(data);
// use
$('button').click(function(){
$(this).hide();
});
});
You need to delegate the event to the static parent:
change this:
$('button').click(function(){
to this:
$(document).on('click', 'button', function(){
because your content is getting loaded via ajax call so initially it was not available in the dom where it is getting loaded so in that case your direct event binding won't work.
To get this work one has to delegate the event to the static parent and in your case you can delegate to body or document itself to get it working.
I think the problem is the click handler registered to the button element is not getting triggered....
The solution is event delegation
$(document).on('click', 'button', function(){
$(this).hide();
});
When you use a normal event registration model, it will register the handlers directly to the targeted which are present in the dom at the point of the handler registration execution. So elements which are added later dynamically will not get those handlers.
The solution to this is to use event delegation, in this model the handler is registered to a ancestor element which will be present when the page is loaded with the a selector to filter out the source element. This makes use of event propagation - events happening in an element is propagated to all the ancestor elements(there are few exceptions like focus event). So an event happening in an element gets propagated to the ancestor element in one of them the handler is registered then the events source element(event.target) and its ancestors is matched against the selector passed as the second parameter, if it is satisfied then the handler is executed.
Related
I have a heading.html file that is being loaded into my index.html.
heading.html
<header id="header">
<div class="logo"></div>
<nav>
Home
About Me
Why Me?
Contact
</nav>
</header>
Then in my javascript file where I am loading in this file, it doesn't let me do any other functions.
functions.js
$( document ).ready(function() {
$(function(){
$("#includedHeader").load("/assets/_includes/header.html");
});
$(function(){
$("#includedFooter").load("/assets/_includes/footer.html");
});
$(function(){
$("#includedWhyme").load("/assets/_includes/why-me.html");
});
$(".slide-section").click(function(){
alert('clicked');
});
});
As you can see I'm trying to make a alert popup just to test if it is working but it doesn't.
Is there a way where I can still use other functions on these html files that are being loaded.
When you're binding the event like this $(".slide-section").click(), the element is not there yet. The .load() is still grabbing the contents from the server.
You can, however, use on method in the document (delegated events). It does a live event attachment (the event will be catched even if the element only exists in the future).
From the .on() docs:
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.
Another suggestion (if I might) is to remove $(function(){} from around your load calls. $(handler) is a shorthand for $(document).ready(handler). So, as if you're calling it once, you don't need them anymore.
So, my suggestion would be something like this:
$( document ).ready(function() {
$("#includedHeader").load("/assets/_includes/header.html");
$("#includedFooter").load("/assets/_includes/footer.html");
$("#includedWhyme").load("/assets/_includes/why-me.html");
});
$(document).on("click", ".slide-section", function(){
alert('clicked');
});
Don't Use directly click() method.. it would not work if the content is not already in the document..instead of this use .on() method to specifie click method its delegate have the advantage that they can process events from descendant elements that are added to the document at a later time.
so i from my point of view use following-
$(document).on("click", ".slide-section", function(){
alert('clicked');
});
I have a button that is loaded into my page using ajax:
<button id="submit">Submit</button>
I am using this code on the page that the button is being loaded into:
<script type="text/javascript">
$(function() {
$("button#submit").click(function(){
alert('Submit Clicked');
});
});
</script>
Why is it not detecting the click from the ajax content?
When you attach the click event you attach it to the existent elements in the DOM, when the ajax content comes, new DOM elements are created and the event wasn't attached to them.
One option is to use events delegation a way (but not recommended) to do it is using the document to read the event
$(document).on('click', 'button#submit', function(){
//do something
});
A better way is put the delegation to the element which gets the new content, lets assume is a form with an id formElement, It would be something like
$("#formElement").on('click', 'button#submit', function(){
//do something
});
Using that event delegation the new content from ajax will fire the click event.
PD if you have an ID in a element just use the id, like #submit, It makes a faster selector than tag#id because It used getElementById internaly
In your code you have attached the event handler to buttons before the button is created. You need to attach the handler afterwards. Add the handler in the ajax success() function instead, after you have created the button, and everything will work ok.
Its because its dynamically added button.For that you have to use on() method try following
$(document).on('click', 'button#submit', function(){
alert("hi");
});
I am building a Windows 8.1 Store application with WinJS. When the user queries some search results show up in a <p class="searchresults">content</p> tag.
I'd like to add an event handler to the .searchresults class. I've done the following:
$('.searchresults').on('click', function() {
console.log("clicked");
});
I've tried even without .on()
$('.searchresults').click(function() {
console.log("clicked");
});
However the event never gets fired. I've set up a breakpoint, so I can see when it fires - but that never happens
I've tried to add an event handler via the WinJS way:
Microsoft.Maps.Events.addHandler(document.getElementsByClassName("searchresults"), 'click', myfunc);
Without success.
Any ideas why this is happening?
I will guess that you are creating the <p class="searchresults">content</p> object AFTER you try to install the event handler (a common problem with dynamic content). That will not work with normal event handling because the DOM object does not exist when you try to add the event handler to it.
If this is the case, then you need to use delegated event handling like this:
$(document.body).on('click', '.searchresults', function() {
console.log("clicked");
});
This will allow you to dynamically create the searchresults content at any time and the event handler will still fire via event delegation (events propagate up to their parents).
You haven't shown the HTML around the search results content, but the most optimal way to do this is to select the closest static parent to the search results (a parent that is not dynamically created and already exists at the time you attach the event handler) and attach the event to that:
$(closest static parent selector).on('click', '.searchresults', function() {
console.log("clicked");
});
I'm using jQuery's .on() event handler and it's only working when I use $(document).
This works:
$(function() {
$(document).on("click", ".search .remove", function(e) {
console.log("clicked");
});
});
This does not work:
$(function() {
$(".search .remove").on("click", function(e) {
console.log("clicked");
});
});
Nothing happens on that second one...no errors or anything. It just doesn't fire.
You are using two different syntaxes of .on which have two very different outcomes.
Your first is:
$(context).on("event","targetselector",handler)
This binds the event to context, and any events of type event that gets to the context that has an e.target that can be selected with targetselector will trigger the handler with e.target as the context. this is commonly known as event delegation.
Your second syntax is
$(targetselector).on("event",handler)
In this case, the event is bound directly to the elements currently on the page that match targetselector, not future elements. This is essentially the same as the old .bind.
Your second example doesn't work because your elements are created dynamically. When using .on() with dynamically inserted elements, you have to bind it via an element that isn't inserted dynamically, i.e. one that exists on the page at load time.
You can continue to use document as an ancestor element but in terms of performance you might want to find an element closer in the DOM to ".search .remove".
From the jQuery docs on .on():
Event handlers are bound only to the currently selected elements; they
must exist on the page at the time your code makes the call to .on().
To ensure the elements are present and can be selected, perform event
binding inside a document ready handler for elements that are in the
HTML markup on the page. If new HTML is being injected into the page,
select the elements and attach event handlers after the new HTML is
placed into the page. Or, use delegated events to attach an event
handler, as described next.
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.
Your first method is the on() equivalent for the deprecated method live(). Probably your elements get inserted dynamically after the page loading has finished.
You could rewrite your code like following and it should work:
$(function() {
$(".search").on("click", ".remove", function(e) {
console.log("clicked");
});
});
I am a bit confused, I have a bunch of elements that get added via jquery using a ajax call and I want to attach a click handler to them (there could be a lot).
But I have no idea how to even begin this, I looked at .on and it is really confusing. I want to attach a click event handler for a certain class so that when I click on it, I get the this.id and then do stuff with it.
What you're trying to do is called event delegation.
You want to set the event listener on a higher element in the DOM that'll never change, but only fire off the event handler if the child element that has been clicked matches a specific selector.
Here's how it's done with jQuery's .on():
$(document).on('click', '.your-selector', function(){
alert(this.id);
});
P.S. You could probably apply the event listener to an element lower down in the DOM tree...
This will get you the id of a clicked element with the class "test"...
$(".test").on("click", function() {
var id = $(this).attr("id")
});
You'll need to run that after the ajax call returns. It will only bind the click event to elements that exist when it runs, so it's no good at document.ready.