Does anyone know what I'm doing wrong here?
var spanclickhandler = $('.officeapprovalspan').click(function () {
// do some stuff
});
Basically, I have this spanclickhandler. Anything with the class officeapprovalspan on loading the page gets this assigned to its click event. No problems there.
In another place I have the code:
$(this).replaceWith('<span class="officeapprovalspan">wero<span>');
$(document).on('click', '.officeapprovalspan', spanclickhandler);
So I'm replacing some HTML with a new span of this class. I use the on to add the click event to the spans of class officeapprovalspan. I gather I have to do this because the new span will not have the click handler attached to it.
So that's OK, but when I click the new span I get this error:
Anyone know what I'm doing wrong and how to fix?
The click method doesn't return the event handler, it returns the jQuery object. Define the event handler first, and use it in the click method:
var spanclickhandler = function () {
...
do some stuff
...
};
$('.officeapprovalspan').click(spanclickhandler);
This chunk of code doesn't do what you think it does (I'm pretty sure that handler function isn't returned):
var spanclickhandler = $('.officeapprovalspan').click(function () {
...
do some stuff
...
});
I suggest you code it like this, which should work:
var spanclickhandler = function () {
...
do some stuff
...
}
$('.officeapprovalspan').click(spanclickhandler);
What you want to do is:
var spanclickhandler = function () {
...
do some stuff
...
};
$(this).replaceWith('<span class="officeapprovalspan">wero<span>');
$('.officeapprovalspan').on('click', spanclickhandler);
OR BETTER
$(document).on('click', '.officeapprovalspan' function () {
...
do some stuff
...
});
// Because 'on' will attach event on DOM element even if they are not created yet, if you define a selector descendant inside. You can replace `document` by the nearest top parent of all your `.officeapprovalspan` and it will improve performance. `document` is not really optimal here
$(this).replaceWith('<span class="officeapprovalspan">wero<span>');
spanclickhandler returns a jQuery object, $('.officeapprovalspan') in this case. You need to either create a separate function or use event namescapes.
Can you just do this:
$(this).replaceWith('<span class="officeapprovalspan">wero<span>').click(spanclickhandler);
Related
I've tried to simplify it, simple enough to make my question clearer.
The alert 'I am a boy' didn't popup with even after the addClass has been executed.
Here is my code:
$(".first").click(function () {
var a = $(this).html();
if (a=='On') {
$(this).removeClass('first').unbind().addClass('second');
$(this).html('Off');
}
});
$(".second").click(function () {
alert('I am a boy');
});
<button class="first">On</button>
This behavior is because you are apply a class to an element after the DOM has loaded, in other words dynamically. Because of this, your event listener attached to the control for '.second' isn't aware of the newly added class and doesn't fire when you click on that control.
To fix this, you simply need to apply your event listener to a parent DOM object, typically $(document) or $('body'), this will ensure it is aware of any children with dynamically added classes.
As George Bailey said, you can refer here for a in depth explanation.
In regards to your specific code, the fix is to simply adjust it as so:
$(".first").click(function () {
var a = $(this).html();
if (a=='On') {
$(this).removeClass('first').unbind().addClass('second');
$(this).html('Off');
}
});
/* Changed this:
$(".second").click(function () {
alert('I am a boy');
});
*/
// To this:
$(document).on('click', '.second', function () {
console.log('I am a boy');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="first">On</button>
The function you pass to $.post doesn’t run until later (a callback). So the class is added after you try to select it. Do it inside the callback, the same way you added the class (and you don’t need to select that class, just use $this)
i have this HTML code on a page when my page loaded:
<div class="divmain">Add
<span class="spn">123</span>
</div>
when you click on that span it will create another span and show hi alert to you,
when the page loaded for the first time it works fine and write another span on that dive as the same the old span but after that if you click on the new span it works not.
i did some test and found if i add this code :
$('.spn').on("click", function (e) {
showalert(this);
});
on the "spanwriter" function it will works , i mean if that function be like this:
function spanwriter(master) {
var rows = '<span class=\'spn\'>123</span>';
$('.divmain').html(rows);
<------- this event must be add here until it --------------->
$('.spn').on("click", function (e) { works
showalert(this);
});
}
why i should add click event at the end of wrote content until span can get that event and works?
i used jquery-1.10.2.js on my sample
my all codes are:
$(function () {
$('.divmain').on("click", function (e) {
spanwriter(this);
});
$('.spn').on("click", function (e) {
showalert(this);
});
});
function spanwriter(master) {
var rows = '<span class=\'spn\'>123</span>';
$('.divmain').html(rows);
}
function showalert(master) {
alert("hi");
}
you have to do the same but with document.on("click")
$(document).on("click", ".buttonClass", function() { console.log("inside"); });
$('.divmain').on("click" make a kind of binding when document is loaded, so when you add dynamix elements to the dom it is noit catched. Whith the use od document.on, it works even if you add dynamic content to the document.
The simplest and best solution to your problem is to attach the event listener to a parent element in the dom and pass the second parameter of the on() method as described in the jQuery documentation (http://api.jquery.com/on/)
In other words you should have something along the lines of:
$('body').on("click", ".spn", function (e) {
showalert(this);
spanwriter(this);
});
and then have the spanwriter() add the new span to the parent of the element it's been called upon.
I hope this is what you were looking for and answers your question.
I am learning JavaScript and jQuery, so I apologize in advance if this is a stupid question.
(function ($) {
$.fn.addDiv = function () {
this.append('<div></div>');
return this;
};
}(jQuery));
$('div').click(function () {
$('body').addDiv();
});
In the code above, I have written a simple jQuery plugin which appends a <div> element to the current value of this.
Now, after I click on an element and add some <div> elements, I realize that the click handler in not associated with the newly appended elements. This seems perfectly acceptable since naturally when the handler function was bound, it was to only the ones that existed and hence were present in the $('div') object.
Now, I know that binding the handler to all <div> elements within the plugin is as simple as follows.
(function ($) {
$.fn.addDiv = function () {
this.append('<div></div>');
$('div').click(function () {
$('body').addDiv();
}); // added this statement
return this;
};
}(jQuery));
But I'm sure that there is a better way to handle such event binding. This clearly duplicates code. So what is the best practice with regards to such event binding to elements that the plugin itself adds?
This is meant to be an educational example, please do not consider it to be any kind of use case and give me alternative solutions.
http://jsbin.com/jokururiyaca/1/edit
Edit: I know that some people recommend the use of .selector but it is deprecated in jQuery 2. Also, using it doesn't change the fact that the event handling code is still duplicated within the plugin.
This is one way you could solve your problem of re-binding the click handler to all elements.
You can create the DOM element using $('<div></div>'), add the click handler to only that element, using $('<div></div>').click(...), and then append it to the body with $('<div></div>').click(...).appendTo("body").
Example:
(function ($) {
$.fn.addDiv = function () {
$('<div></div>').click(function () {
$('body').addDiv();
}).appendTo("body");
return this;
};
}(jQuery));
Usually Event Delegation would be used to handle events on future elements.
Example:
(function ($) {
$.fn.addDiv = function () {
this.append('<div></div>');
return this;
};
}(jQuery));
$(document).on("click", "div", function(){
$('body').addDiv();
});
I have an element, a div, for example. And attach an event 'click' to it. In jQuery, it would be:
$('#myDiv').click(function(){
$(".class1").show();
})
Now, I would like to assign a new function "myDiv #", replacing the old. I am doing so:
$('#myDiv').click(function(){
$(".class23").hide();
})
But when I run the 'click' on the div, the function I assigns the beginning of this doubt is performed.
Question: How to remove the function that will run with the click event attributed to an element? (No recreate the element with the new click event...)
You want .unbind.
You can either remove all previous bound functions:
$('#myDiv').unbind('click');
Or if you only want to unbind one specific function:
var show = function() {
$(".class1").show();
};
$('#myDiv').click(show);
and then:
$('#myDiv').unbind('click', show); // unbind first function
$('#myDiv').click(function() { // bind second function
$(".class23").hide();
});
Note that .click(func) is just a shortcut to .bind('click', func).
If you know you'll only want to handle one click on an element, you can use one() which automatically unbinds after a single click:
$("#myDiv").one("click", function() {
$(".class1").show();
$("#myDiv").one("click", function(){
$(".class23").hide();
});
});
Use the JQuery unbind function to remove all click events
$('#myDiv').unbind('click');
Add a counter on the first click event.
var counter = 0;
$('#myDiv').click(function(){
if(counter>1){
$(".class23").hide();
}
else
$(".class1").show();
counter++;
})
just an example..
Is it possible to add a onclick event to any button by jquery or something like we add class?
function onload()
{
//add a something() function to button by id
}
Calling your function something binding the click event on the element with a ID
$('#id').click(function(e) {
something();
});
$('#id').click(something);
$('#id').bind("click", function(e) { something(); });
Live has a slightly difference, it will bind the event for any elements added, but since you are using the ID it probably wont happen, unless you remove the element from the DOM and add back later on (with the same ID).
$('#id').live("click", function(e) { something(); });
Not sure if this one works in any case, it adds the attribute onclick on your element: (I never use it)
$('#id').attr("onclick", "something()");
Documentation
Click
Bind
Live
Attr
Yes. You could write it like this:
$(document).ready(function() {
$(".button").click(function(){
// do something when clicked
});
});
$('#id').click(function() {
// do stuff
});
Yes. Something like the following should work.
$('#button_id').click(function() {
// do stuff
});