I have a small issue. So i have a php page whose content return a button using ajax such as shown below:
HTML part:
<a href="#" class="unit_register_button">
Register
</a>
jQuery part:
$('a.unit_register_button').click(function(e){
e.preventDefault();
alert('yaay');
});
Problem:
The button does not respond to the jQuery.
I have tried copying the exact line of html with the button to the page directly and works perfect when I click.
What is the solution and why does the button not work when it is displayed using ajax?
you should use event delegation for that
$(document).on("click","a.unit_register_button",function(e){
e.preventDefault();
alert('yaay');
});
Event delegation allows you to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.
There is couple ways, one of them is by using on function:
$(document).on('click', 'a.unit_register_button', function(e){
e.preventDefault();
alert('Alert message');
});
And another is with delegate function:
$(document).delegate('a.unit_register_button', 'click', function(e){
e.preventDefault();
alert('Alert message');
});
Here jsfiddle with working examples.
Hope this helps.
Related
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");
});
Attempting to add a click event to a button that is nested between multiple elements (ul, div.col, li, div.panel, div.panel-body). I am able to access it with the below code, however as if I click on the page more than a few times the console.logs begin to loop and execute thousands of times.
I am nearly positive it is the nesting of the functions causing this. But I do not have a thorough enough background in JQuery to be able to tell exactly what the browser is doing.
Here is my JQuery code:
$('#displayList #col1').click(function(){
console.log('clicked col');
$('li').click(function(){
var id = $(this).attr('id');
console.log(id);
$('div.panel').click(function(){
console.log('clicked panel');
$('div.panel-body').click(function(){
console.log('clicked panel body');
$('button').click(function(){
console.log('clicked button');
return;
});
return;
});
return;
});
return;
});
return;
});
Could one of you wonderful JQuery gurus explain what is causing this bug and point me in a better path for checking if the button has been clicked or if it hasnt(just the panel was clicked).
Also, does anyone know a good and preferably free debugging program that I can use to step through JQuery code execution by execution?
Thank you so much for your knowledge
You are binding an event handler inside another event handler. So whenever the later event occurs, new handlers are added, Eventually causing multiple handlers for same event on same element.
Your code should look something like
$('#displayList #col1').click(function(){
console.log('clicked col');
});
$('li').click(function(){
var id = $(this).attr('id');
console.log(id);
});
$('div.panel').click(function(){
console.log('clicked panel');
});
$('div.panel-body').click(function(){
console.log('clicked panel body');
});
$('button').click(function(){
// The following will be executed when the button is clicked
console.log('clicked button');
});
Assume you have the following markup:
<div id="container>
<div id="parent">
<button>Click Me!</button>
</div>
</div>
And the event handlers:
$("#container").click(function(){
console.log("container got a click!");
});
$("#parent").click(function(){
console.log("parent got a click!");
});
$("#parent button").click(function(){
console.log("button got a click!");
});
Now if you click the button output will be
//button got a click!
//parent got a click!
//container got a click!
When you click an element, all of it's ancestors will also receive a click event by default, and the corresponding event handler will be called, if any - This is called event bubbling.
If you don't need any specific functionality then you don't need a handler so bubling won't hurt.
However, You can prevent this behaviour by calling the stopPropagation() method of event object inside the event handler:
$("#parent button").click(function(e){
e.stopPropagation();
console.log("button got a click!");
});
output will be
//button got a click!
There is one more event propagation method in some browsers (Only event bubbling model is supported by all the major browsers), you can read about it in detail #quirksmore: Event order
As DFTR mentioned in comments,
Visual studio allows break points in javascript code, when launching an application within internet explorer. Another debugging tool is firebug, which is a pretty neat firefox extension
Might help you.
if you need to bind event to button, you should use descendant selector
$('#displayList #col1 li div.panel div.panel-body button').click(function() {
console.log('clicked button');
});
Hi i always use this example code to make a div work as link.
<div onclick="location.href='http://www.example.com';" style="cursor:pointer;"></div>
The problem is i have inserted an other javascript action inside (this action need to stay on the current page) the problem is Not the first click but the second..
This javascript actions its an ajax function that "change" that html.. in the fiddle where i have no ajax, its working great, on first, second, third, any clic..
Here is the code http://jsfiddle.net/HzsH9/4/
Im using.. Jquery, also this is the anti propagate code im using
$("a").bind("click", function(e){ alert("clicked!"); e.stopPropagation() });
The outer div class is class="listingsRow"
and the inside javascript goes here
<a id="btn_remove_114" name="btn_remove_114" onclick="ajaxFavouratesRemove(1,114,375);">
<div class="fav"></div></a>
After ajax success, its changed for this
<span id="spadd114"><a id="btn_add_114" name="btn_add_114" onclick="ajaxFavouratesAdd(114);"><div class="nofav"></div></a></span>
Also i just found this, but i cant manage to do the same how to stop event propagation with slide toggle-modified with the updated code.
Classic case of event delegation
$(".listingsRow").on('click','a',function(e){
alert('clicked');
e.stopPropagation();
})
$('#singles_114').click(function(e){
e.stopPropagation()
});
I am using jQuery and I have loaded a bunch of JavaScript for a web page which works as expected. However when I try to add the following code to trigger a button click, the button is not activated:
$(document).ready(function(){
$('.add_link').click();
});
I am wondering what I am doing wrong? I have this bit of code in a separate file that gets loaded after all the other JavaScript files are loaded. Any hints?
$('.add_link').click();
Maybe the button is not found, because it does not have the specified class. Look for typos or maybe you just forgot to set the class for the button?
What should happen, when you click the button?
What is the html code for this?
I have found the answer after playing around some more. Since I am using Drupal, I need to use a closure to make sure it works correctly. The correct code should be:
jQuery(document).ready(function($){
$('.add_link').click();
});
It is always the small things that trip you up. Thanks for all the responses.
HTML:
<button class="add_link">Click ME</button>
Javascript:
$(document).ready(function(){
$('.add_link').click(function(event){
//I'm the event handler
console.log(event);
alert(".add_link clicked!!!");
});
});
Other examples:
$(document).ready(function(){
//Named function
function myHandle(event){
//I'm the event handler
console.log(event);
alert(".add_link clicked!!!");
}
//adding event with event alias
$(".add_link").click(myHandle);
//adding event with jQuery.on
$(".add_link").on("click", myHandle);
//adding event with jQuery.on and delegation
$("body").on("click", ".add_link", myHandle);
});
I use jQuery.on because syntax of delegation and simple event handling is almost the same. jQuery.on is newer then jQuery.bind, jQuery.live and jQuery.delegate too.
jsFiddle
We have legacy pages which have links where target="_blank". On clicking these I'd like to ignore that and run a some JavaScript I have for opening windows.
Is this possible with jQuery, if so what methods/terms should I research?
Thanks in advance
Just use event delegation to prevent the links with target="_blank" from working, example:
$(document).on('click', 'a[target="_blank"]', function(event) {
event.preventDefault();
alert('Prevented');
});
$('a[target=_blank]').click(function(e){
e.preventDefault();
//do what you want here
});
Demo: http://jsfiddle.net/kkhNr/1/
Try this
$('a[target=_blank]').click(function(event) {
event.preventDefault();
// Now make a call to your own function
});
I just wanted to point out that #Roger C's listener is a better solution...if you have any dynamically loaded content on your page (i.e. AJAX or AngularJS single page applications).
This listener listens to the document's clicks and will pickup newly added content without needing to re-add the listener after content changes:
$(document).on('click', 'a[target="_blank"]', function(event) {
event.preventDefault();
alert('Prevented');
});
This listener listens to all selectors found at the time it was called (possibly missing any newly added content):
$('a[target=_blank]').click(function(e){
e.preventDefault();
alert('Prevented');
});