I have some jQuery code like this:
$("#add").click(function(event){
$("#list").append('<a class="remove" href="#">x</a>');
return false;
});
$('.remove').live('click', function(){
alert("123");
});
If one clicked on class=remove I would like it to alert 123. This doesn't happen though. I think this is a simple idea but I must be missing something.
Any ideas?
Thanks.
Live is deprecated, use on
$(document).on('click','.remove',function(){
alert("123");
});
Another way to add element and bind event without delegation:
$("#add").click(function(event){
$("<a />", {
"class": "remove",
href: "#",
text: "x"
}).on("click", function() {
alert("123");
return false;
}).appendTo("#list");
return false;
});
Avoid using live method, since it was deprecated and finally removed in the last version of jQuery.
try on delegate function..since you are apending that to list... you can use #list which is better in performance that the document
$('#list').on('click','.remove', function(){
alert("123");
});
you can go through the link to read more about on() event
Related
I am trying to make some text that changes when you click it, but changes back if you click it again.
It works fine, once. But if i try it a second time, nothing happens.
My HTML:
<div id="text">
<p>TEXT1</p>
</div>
JavaScript/jQuery:
$(document).ready(function(){
$("#text").click(function(){
$(this).html("<p>TEXT2</p>").click(function(){
$(this).html("<p>TEXT1</p>");
});
return false;
});
});
Example:
http://mrkireko.github.io/jQueryExample/
I'd suggest instead:
$('#text p').click(function(){
$(this).text(function(i,t){
return $.trim(t) === 'text1' ? 'text2' : 'text1';
});
});
JS Fiddle demo.
References:
click().
jQuery.trim().
text().
It's because after the first click, you now have two handlers assigned,
The first one still puts the TEXT2 in place, but the second one changes it back.
One correct solution is to use the handler version of .toggle():
$(document).ready(function(){
$("#text").toggle(function(){
$(this).html("<p>TEXT2</p>");
return false;
}, function(){
$(this).html("<p>TEXT1</p>");
return false;
});
});
As #KevinB noted, this version of .toggle() is deprecated. To do your own toggle, you can do this:
$(document).ready(function() {
$("#text").click(function(i){
return function() {
$(this).html(++i % 2 ? "<p>TEXT2</p>" : "<p>TEXT1</p>");
return false;
};
}(0));
});
DEMO: http://jsfiddle.net/NkGZj/
You are binding multiple click handlers to the same element, and they are all executing every time you click. Since the handler to change the text to TEXT1 executes last, that's what you end up with.
See the console.log() output here:
http://jsfiddle.net/tcMx5/
Binding event handlers in event handlers is almost never the right thing to do. Instead, have one handler that checks the current state and toggles the value.
Several answers here, some will work well. Here is another option, using class:
<div id="text" class="state1">
<p>TEXT1</p>
</div>
$(document).ready(function(){
$("#text").click(function(){
var $this = $(this);
if ($this.hasClass('state1')) {
$this.html('<p>TEXT2</p>');
}
else {
$this.html('<p>TEXT1</p>');
}
$this.toggleClass('state1');
});
});
I would lean more towards this solution because it is not dependent on what is actually contained within the element. Unless, of course, you know that it will never change and you can reliably target the string.
You can do something like this:
$( "#text" ).toggle(function() {
this.html("<p>text 2</p>");
}, function() {
this.html("<p>text 1</p>");
});
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery 1.7 - Turning live() into on()
I have with jQuery:
$(".house td[red]").live("click", function() {
alert('ok');
});
but function live is deprecated. How can i use on?
$(".house td[red]").on("click", function() {
alert('ok');
});
not working.
$(".house").on("click", 'td[red]', function() {
alert('ok');
});
have you tried this? You can check in documentation for details. Example from there:
$("#dataTable tbody").on("click", "tr", function(event){
alert($(this).text());
});
So you basically pass a "container" for wrapper. The reason why live is not recommended is that it can be written with "on" syntax like this:
$(document).on("click", '.house td[red]', function() {
alert('ok');
});
which you can see is not very efficient. Probably there's more to that :) so it is good you want to change it.
Use it as -
$(document).on("click", ".house td[red]", function() {
alert('ok');
});
The more efficient way is using .on() with immediate parent of the element -
$('.house').on("click", "td[red]", function() {
alert('ok');
});
Read here for better understanding of difference between live and on
on() is an all-things-to-all-men function that can work in different ways - both with direct and delegated events. live() was a means of achieving delegated events. This is achieved with on() by passing a filter as param 2, and bumping the callback to param 3:
$(".house").on("click", 'td[red]', function() {
alert('ok');
});
It's a three-argument variant, and you get to pick the "bubble" point:
$('body').on('click', '.house td[red]', function() { alert("ok"); });
The difference is that with this, the point at which the actual event handler is placed is under your control (like with the also-deprecated .delegate()). You can pick any parent element you like, which is a nice feature in complicated pages. (In your case, for example, you could put the handler on all the ".house" elements instead of the body.)
$(document).on('click', '.house td[red]', function(){
alert('ok');
});
Document is the static element we wish to attach our handler to.
First param is the event
Second param is the selector
Third param is the functions you wish to run against the selector when the event is fired.
Try this,
$(document).on("click", ".house td[red]", function() {
alert('ok');
});
$(".house td[red]").live("click", function() {
alert('ok');
});
Would be directly converted to this:
$(document).on("click", ".house td[red]", function() {
alert('ok');
});
But you can gain some performance by specifying the closest container that you know will exist at the time of the bind:
$('#someContainer').on("click", ".house td[red]", function() {
alert('ok');
});
$(document).on("click",".house td[red]",function(){
alert('ok');
});
Say I have some code like this which is called on $(document).ready()
$(".someClass").click(function(){
//do something
});
Later on I have some jquery to create an element with the class someClass. Is there anyway to automatically attach the click from above or do I have to manually attach it again?
Yes. It is possible.
$("body").on("click", ".someClass", function() {
// ...
});
Use latest version of jquery and on
$(document).on('click', '.someClass', function(e){
//do something
});
Live is deprecated but you can use it, anyway (not recommended).
$('.someClass').live('click', function(e){
//do something
});
There is live, which also listens for new elements
$(".someClass").live('click', function(){
//do something
});
But, as of jquery 1.7 it has been deprecated. It's advised to use on instead.
But in order to use on, you need a container for the elements you want to bind a handler. Of course you could use body or document but it's better to use a more specific element
$(".someClassContainer").on('click', '.someClass' function(){
//do something
});
There's two easy ways of doing this, the first is with on():
$(".someClassParentElementPresentInTheDOMonDOMReady").on('click','.someClass',
function(){
//do something
});
And the other is to simply assign the click-handler at the point of creation of the new element; I don't know how you're doing that, but an example is below:
$('#addElement').click(
function(){
var newElem = $('<div />',{'class' : 'someClass'}).click(function(){
// do something }).appendTo('.someClassParentElementPresentInTheDOMonDOMReady');
References:
on().
I have a list of checkboxes. I need to know which was was clicked.
I can't do a loop with
if(form1.news[i].checked)
Because there can be others that are already checked.
I've tried using
this.form.id
this.from.checkboxname.id
but it didn't work.
The event object will contain a reference to the element that was clicked.
For example (using YUI to abstract the browser differences for event binding, other libraries do similar things and you can use raw DOM if you don't mind abandoning old-Internet Explorer):
YUI().use('node', 'event', function (Y) {
Y.one('#container').delegate('click', function (e) {
alert(e.target.get('value'));
e.stopPropagation();
}, 'input[type=checkbox]');
});
UPDATED DEMO:
$(function() {
$('#myButton').click(function() {
$('input:checkbox:checked').each(function(i) {
alert(this.value);
});
});
});
If your onclick() function is on the checkbox, this.id should work just fine.
lets say I have
function trigger(){
$('a.pep').each(function(){
$('a.pep').click(function(){
console.log($(this).val());
});
});
}
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
trigger(); //now i do but the others have duplicated trigger
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
});
So it seems that the click event is being applied twice/+ because the console.log is lauched more than once by click
How can i prevent this?
The problem is that you call $('a.pep').click() lots of times. (In fact, you bind as many click handlers as there are matching elements to each element. And then you do it again every time one of them is clicked.)
You should lever the DOM event bubbling model to handle this. jQuery helps you with the on method:
$(document.body).on('click', 'a.pep', function() {
console.log('element clicked');
$(document.body).append('<a class="pep">Click handlers handled automatically</a>');
});
See a working jsFiddle.
Note that I have removed the val call, because a elements can't have a value... Note also that the on method is introduced in jQuery 1.7; before that, use delegate:
$(document.body).delegate('a.pep', 'click', function() {
Small change to your trigger function is all you need. Just unbind the click event before binding to ensure that it is never added more than once. Also, you don't need to use each when binding events, it will add the event to each item automatically.
function trigger(){
$('a.pep').unbind('click').click(function() {
console.log($(this).val());
});
}
You can check using data('events') on any element if the required event is attached or not. For example to check if click event is attached or not try this.
if(!$('a.pep').data('events').click){
$('a.pep').click(function(){
console.log($(this).val());
});
}
you should use jQuery live here because you add DOM elements dynamicly and you want them to have the same click behaviour
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
$('a.pep').live('click', function(){
console.log($(this).val());
});
});
Try:
if($('a.pep').data('events').click) {
//do something
}
i think if you use live() event you dont need to make function
$('a.pep').live('click', function(){
console.log($(this).val());
});