.each + .click (jQuery) - javascript

If I try to run this code:
$('a').each( function(index, element) {
element.click(function(){
console.log('hit');
});
});
It doesn't work, but if I code this one:
$('a').each( function() {
$(this).click(function(){
console.log('hit');
});
});
Everything is ok, someone can help me please? Why is not working when I use element
PD: I know that this solution is the best but I would like to know why is not working before
$('a')click(function(){
console.log('hit');
});

It should be $(element).click(... because element is a DOM Element, not a jQuery object.
$('a').each( function(index, element) {
$(element).click(function(){
console.log('hit');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><a>foo</a>
<p><a>bar</a>
<p><a>baz</a>
There is actually a click method on native Elements, but it serves a different purpose; it invokes a "click" event instead of binding a handler.
And of course to do this without large dependencies, and using modern syntax, it could look like this:
for (const element of document.querySelectorAll('a')) {
element.addEventListener("click", handler)
}
function handler() {
console.log('hit');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><a>foo</a></p>
<p><a>bar</a></p>
<p><a>baz</a></p>

You can use addEventListener
$('a').each( function(index, element) {
element.addEventListener("click", function(){
console.log('hit');
});
});

Related

Remove/add a class and then execute an event on this new class

I use this script to change a class:
$('.fa.fa-plus-circle').each(function() {
$(this).on('click', function () {
$(this).removeClass().addClass("fa fa-minus-circle");
});
});
Then I used
$('.fa.fa-minus-circle').each(function () {
$(this).on('click', function () {
$(this).removeClass().addClass("fa fa-plus-circle");
});
});
So for the first one "fa.fa-plus-circle" that is the default when the page is loading, everything is good and the class changes. But when the class changes I can't do anything else after, JQuery continues to execute
$('.fa.fa-plus-circle').each(function() {
$(this).on('click', function () {
$(this).removeClass().addClass("fa fa-minus-circle");
});
});
Why ??
Thanks in advance
You need to use delegate for this, because you are adding the classes dynamically.
$(document).on("click", '.fa.fa-minus-circle', function() {
$(this).removeClass().addClass("fa fa-plus-circle");
});
$(document).on("click", '.fa.fa-plus-circle', function() {
$(this).removeClass().addClass("fa fa-minus-circle");
});
Also there is no need for looping through the elements for binding the event.
But the recommended approach will be,
$('.fa').click(function() {
$(this).toggleClass("fa-minus-circle fa-plus-circle");
});
Edit
$(document).on("click", ".fa", function() {
$(this).toggleClass("fa-minus-circle fa-plus-circle");
});
It's not .fa-minus-circle when it loads, so the each loop never happens. Even if you removed the each loop (which isn't required) it wouldn't add the listeners because it wouldn't find the selector. So, you have to use the delegates version of on which looks something like this...
$('body').on('click','.fa-minus-circle',function () {
$(this).removeClass().addClass("fa fa-minus-circle");
});
fwiw, you could just use one class and toggleClass Then put all your fa-plus-circle code into the fa class since that is the default behavior.
$('body').on('click','.fa',function () {
$(this).toggleClass("fa-minus-circle");
});
There's a benefit to not removing all classes. There seems no point to removing .fa so that you can add it. Which means that your code should be:
$(function() {
$(document).on("click", '.fa.fa-minus-circle', function() {
$(this).removeClass('fa-minus-circle').addClass("fa-plus-circle");
});
$(document).on("click", '.fa.fa-plus-circle', function() {
$(this).removeClass('fa-plus-circle').addClass("fa-minus-circle");
});
});
And as #AnoopJoshi has pointed out, you can use the .toggleClass() method:
$(function() {
$('.fa').on('click', function() {
$(this).toggleClass('fa-minus-circle fa-plus-circle');
});
});

How to simulate a click event when document onready?

The two method below are not working for me; I need the button click event to fire with the document onready event. (#usrpost is a button element.)
$(function() {
$("#usrpost").trigger("click");
$("#usrpost").live("click",function() {
//do something.
});
});
I've also tried the following:
$(function() {
$("#usrpost")[0].click();
$("#usrpost").live("click",function() {
//do something.
});
});
You need to trigger the event after the handler is added(apart from the spelling issue, also assuming you are using jQuery < 1.9)
$(function () {
$("#usrpost").live("click", function () {
//do something.
});
//fire it after the handler is added
$("#usrpost").click();
});
Note: If you are using jQuery >= 1.7 use .on() instead of .live()
$(function() {
$("#usrpost").on("click", function() {
//do something.
});
$("#usrpost").click();
});
You had a typo in "function"
You must call the .click() after bind the event:
$(function() {
$("#usrpost").live("click",function() {
//do something.
});
$("#usrpost")[0].click();
});
.live() is also now deprecated in favour of .on():
$(function() {
$('body').on('click', "#usrpost", function() {
//do something.
});
$("#usrpost")[0].click();
});
You can trigger the event too
$("#usrpost").trigger("click");

HTML content is not getting on Jquery click function

In my code I have the following:
$(document).ready(function(){
$("input#Addmore").click(function(){
$('div#add_div').append("<a class='remove' href='#'>X</a>");
});
});
This code on click of add more button and I want to remove parent div of above added code on click of "X" by jquery. for that purpose i am using this code
$("a.remove").click(function(){
$(this).closest("div").remove();
});
But the code is not working because jQuery did not getting append anchor code. Can any one tell me the solution?
You need to delegate the event to the nearest static element. Try this:
$('#add_div').on('click', 'a.remove', function() {
$(this).closest("div").remove();
});
Or if you are using an older version of jQuery (less than 1.7) use delegate() like this:
$('#add_div').delegate('a.remove', 'click', function() {
$(this).closest("div").remove();
});
Try this
$('#add_div').delegate('a.remove', 'click', function() {
$(this).closest("div").remove();
});
Or you can try this:
$("input#Addmore").click(function(){
$("div#add_div").append("<a class='remove' href='javascipt:;' onclick='remove(this);return false' href='#'>X<br/></a>");
});
and here is remove function:
window.remove = function(obj)
{
$(obj).closest('div').remove();
}
see here : http://jsfiddle.net/Hvx2u/3/

Jquery dynamically create link

I have a piece of JQuery that creates a row in a table and in one of the cells there is an X that is surrounded by a class. When it is dynamically created and then clicked on the click listener does not fire.
Here is the code.
$('#add').click(function() {
$( '#table' ).append('<td class="x">X</td></tr>');
});
$('.x').click(function() {
alert('Fired');
});
Since the <td> element does not yet exist when you register your event handler, you have to use live() or delegate() for the handler to be triggered later:
$(".x").live("click", function() {
alert("Fired");
});
$(".x").live("click", function()
{
alert("Fired");
});
Live adds events to anything added later in the DOM as well as what's currently there.
Instead of
$('.x').click(function() {
alert('Fired');
});
Change to this
$('.x').live('click', function() {
alert('Fired');
});
It binds the click function to any created element with class x
You need to use the .live function for content that's dynamically generated.
so replace
$('.x').click(function() {
with
$('.x').live('click',function() {
You are first creating the listener to all .x elements (of which there are presumably zero), then later adding new .x elements.
There are two solutions: one is to use jQuery live, the other is to rewrite your code:
var xClickHandler = function() {
alert('Fired');
};
$('#add').click(function() {
$('#table').append(
$('<td class="x">X</td></tr>').click(xClickHandler);
);
});
Use live instead of click:
$('.x').live("click", function() {
alert('Fired');
});
The html you are appending to the table has a typo, you have missed out the beggining tr tag:
$('#add').click(function() {
$( '#table' ).append('<tr><td class="x">X</td></tr>');
});
$('.x').click(function() {
alert('Fired');
});
I think you need to use the live method. http://api.jquery.com/live/
$('.x').live('click', function() {
// Live handler called.
});

run function at ready and keyup event

Is there another in jquery to run a function at page load and at a keyup event instead of the way I'm doing it?
$(function() {
totalQty();
$("#main input").keyup(function() {
totalQty();
});
});
Disregarding live or delegate optimizations, you can trigger an event like this:
$(function() {
$("#main input").keyup(function() {
totalQty();
}).filter(":first").keyup(); //Run it once
});
No need for the filter if it's not on multiple elements, just leave it out in that case.
You can use $(document).ready event to run functions on load:
$(document).ready(function(){
/* your code here */
});
Here's what I would do (jQuery 1.4+ )
$(document).ready(function() {
totalQty();
$("#main").delegate("input","keyup",function() {
totalQty();
});
});
You could use $.live(), which does event delegation, which is MUCH more efficient than created an event listener for every single input tag...and then missing any dynamically created ones. Try the following:
$(document).ready(function() {
totalQty();
$('#main input').live('keyup', function() {
totalQty();
});
});

Categories