jQuery click event when triggered programatically - javascript

I have a link with an inline onclick event:
click
I registered an additional function on the onclick event:
jQuery("#addMoreOptions").live('click',function(){
console.log('clicked');
});
Which works fine when I click on the link on the browser, but not when I simulate programmatically:
jQuery("#addMoreOptions").click();
The programatical version triggers the inline event but not the "live" one.
When you have multiple functions attached to an event, what order does it use?

I am pretty sure this is caused by the order of things happening.
If you look at this live example you'll see everything works as expected. This is because the event is registered, and then called. The code looks like:
jQuery(document).ready(function(){
jQuery("#addMoreOptions").live('click',function(){
console.log('clicked');
});
$('#addMoreOptions').click();
});
function somefunction()
{
alert("clicked");
}
When the page loads, you get an alert and a console.log.
Now with the very small change of putting the $('#addMoreOptions').click(); before registering the event as in this live example you only get the alert from the inline function.
For reference the code is
jQuery(document).ready(function(){
$('#addMoreOptions').click();
jQuery("#addMoreOptions").live('click',function(){
console.log('clicked');
});
});
function somefunction()
{
alert("clicked");
}

An alternative way of triggering a click event would be to use the .trigger() function:
jQuery('#addMoreOptions').trigger('click');

Related

Use of Binding after Unbinding

I found a code as shown below.
Html code:
<div id="myButton">Click Here</div>
JQuery Code:
$("#myButton").unbind("click").bind("click",function(){
alert("Working")
});
What is the need of unbind("click") before binding the element?
It is also working if unbind is not used. like shown below
$("#myButton").bind("click",function(){
alert("Working")
});
Which one is best? what is the difference?
This only makes sure, that there is no other click event listener attached. So your handler will be the only handler acting upon clicking the #myButton
Edit: as #T.J. Crowder noted in the comments, unbind() will not affect handlers attached in different way than by calling bind().
It is also worth noting, that:
as of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements
(excerpt from the jQuery.unbind() doc). In fact, unbind() is implemented internally by the off() method).
Consider:
$("#myButton").bind('click', function () {
console.log('click 1');
});
$("#myButton").unbind('click').bind('click', function () {
console.log('click 2');
});
// When clicked, prints "click 2"
Versus:
$("#myButton").bind('click', function () {
console.log('click 1');
});
// note: no unbind here
$("#myButton").bind('click', function () {
console.log('click 2');
});
// When clicked, prints "clicked 1" followed by "clicked 2"
By unbinding "click" event on an element, you are actually removing all the onclick events associated with that element. i.e. if your html form's input field has an onclick event and it calls a function, it will be unbound. After an unbind, you are binding another click event which will call your function onclick of that element.
$("#myButton").unbind("click").bind("click",function(){
alert("Working")
});
jQuery bind() function is used to attach an event handler to elements, while the unbind() is used to detached an existing event handler from elements. please see a demo http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-bind-unbind-example.html
Without url of this html code , i'm not sure that #myButtonelement whether has other click handler attached ,but what is certain is unbind method remove all the handler on this element , i think the author only want to trigger one click event.
Also, you can see if there is other event handler on debug inspector of browser.
Hope this will help you.

jQuery click event not triggering button action

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

jQuery trigger('click') not working with Jasmine-jquery

This is my test code:
describe("Login", function(){
beforeEach(function(){
loadFixtures('login-fixture.html');
})
it("should enable the button when checking 'remember password'", function(){
$('#remember').trigger('click');
expect($('#keepIn')).not.toBeDisabled();
});
});
And this is my production code:
$(document).ready(function(){
$('#remember').click(function(e) {
if($('#remember').is(':checked'))
{
$('#keepIn').removeAttr('disabled');
}
});
});
This is not working, the production code never gets called. I have put alerts before and after the trigger event and after the trigger the checkbox is checked, but the .click function does not get called.
Any thoughts on why is this happening?
Without seeing the rest of the code, I'm assuming the "login-fixture.html" contains the "#remember" checkbox. If so, it's loading after the DOM loads. Meaning that the 'click' event you want assigned will only apply to previously loaded elements. The jQuery on() event will assign any event you want to newly loaded elements. You might want to try adding a on() event to that id. Something like:
$(function(){
$('#remember').on('click', function(){
if($('#remember').is(':checked')){
$('#keepIn').checkboxradio('enable');
}
});
});
Hope that helps.
See: http://api.jquery.com/on/

In jQuery, is there any way to only bind a click once?

I have an ajax app that will run functions on every interaction. I'd like to be able to run my setup function each time so all my setup code for that function remains encapsulated. However, binding elements more than once means that the handler will run more than once, which is obviously undesirable. Is there an elegant way in jQuery to call bind on an element more than once without the handler being called more than once?
User jQuery one function like Tom said, but unbind the handler each time before binding again. It helps to have the event handler assigned to a variable than using an anonymous function.
var handler = function(e) { // stuff };
$('#element').unbind('click', handler).one('click', handler);
//elsewhere
$('#element').unbind('click', handler).one('click', handler);
You can also do .unbind('click') to remove all click handlers attached to an element.
You could attach the event to document with the one() function:
$(document).one('click', function(e) {
// initialization here
});
Once run, this event handler is removed again so that it will not run again. However, if you need the initialization to run before the click event of some other element, we will have to think of something else. Using mousedown instead of click might work then, as the mousedown event is fired before the click event.
You can also use .off() if unbind doesn't do the trick. Make sure the selector and event given to .off exactly match the ones initially provided to .on():
$("div.selector").off("click", "a.another_selector");
$("div.selector").on("click", "a.another_selector", function(e){
This is what worked for me in resolving the same ajax reloading problem.
The answer from Chetan Sastry is what you want. Basically just call a $(element).unbind(event); before every event.
So if you have a function like loadAllButtonClicks() that contains all the
$(element).on("click", function (){});
methods for each button on your page, and you run that every time a button is clicked, this will obviously produce more than one event for each button. To solve this just add
$(element).unbind(event);
before every
$(element).on("click", function (){});
and it will unbind all events to that element, then add the one click event.

Event handler does not apply to created element

I have put some easy codes below to clarify the title.
I am using JQuery 1.3.2
Here is my JS:
$(document).ready(function() {
$('#test').click(function() {
$('#result').html('hello world');
});
$('#hello').click(function() {
$('#result').html('Test #2');
});
});
In html, I have a hyperlink id='test' and a div with id='result'. What I expect this JS code to is when I click on test, it shows the "Hello World". After that, when I click the "Hello World", it supposed to show "Test #2"
Any suggestion is very helpful...
As hobodave says, this has nothing to do with Ajax.
The issue is that the click() functions are attached to the HTML when the document is loaded (on DOM ready). However, at that point the Hello world div doesn't exist yet. When it's created, it has no click event.
What you need is either to add the click() when the new div is added, or alternatively use the live() function to attach your event handlers.
$(document).ready(function() {
$('#test').live('click',function() {
$('#result').html('hello world');
});
$('#hello').live('click',function() {
$('#result').html('Test #2');
});
});
That said, an even easier method for the functionality you want is just to use hide() and show() on two already-existing divs.
First, your question has nothing to do with AJAX. This is pure javascript. The onClick listeners you are defining above are bound to the appropriate elements on page load (specifically the DOM Ready event). When the page loads, there is no element with id="hello", thus it doesn't get the listener bound to it.
What you need to do is nest the listener binding for id="hello" inside the click event for id="result"
e.g.
$(document).ready(function() {
$('#test').click(function() {
$('#result').html('hello world');
$('#hello').click(function() {
$('#result').html('Test #2');
});
});
});
It's because the click event handler for element with id="hello" that you set up in document ready does not get bound to the element as it does not exist in the DOM until the element with id="test" is clicked.
One way to resolve this would be to use event delegation and the live() command.
Another way would be to define the click event handler at the same time as adding the element to the DOM. The following will work fine in this scenario
$(function() {
$('#test').click(function() {
$('#result')
.html('hello world');
$('#hello').click(function() {
$('#result').html('Test #2');
// to prevent event propagation
return false;
});
// to prevent event propagation
return false;
});
});
There are specific jQuery commands for appending elements to other elements, the ones that would work well in this scenario are append() and appendTo(). This is an example using appendTo()
$(function() {
$('#test').click(function() {
$('hello world')
.click(function() {
$(this).replaceWith('Test #2')
})
.appendTo('#result');
});
});

Categories