JS: append cannot find attr - javascript

$(".btn").click(function()
{
$(".content").append(
"<div class='randomDiv' id='1'></div>"
);
}
If above is "active" then I cannot:
$(".randomDiv").click(function()
{
alert($(this.attr("id")));
}
I've googled and found out that it is because JS is loaded before I append, but haven't found a solution how to "register after load" on JS.

Either:
Attach the event handler when you create the element
$(".btn").click(function() {
$("<div class='randomDiv' id='1'></div>")
.on("click", myFunction)
.appendTo(".content");
}
function myFunction() {
alert($(this.attr("id")));
}
… so the element does exist when you bind the event handler
Use a delegated handler
$(document).on("click", ".randomDiv", function () {
alert($(this.attr("id")));
});
… that captures all the click events as they bubble up the document and checks which elements they came from.

$(".content").on('click', '.randomDiv', function()
{
alert($(this.attr("id")));
}
$(".content") can be replaced with any existing parent item of randomDiv. Say content div is inside page-left div then above code can be written as
$(".page-left").on('click', '.randomDiv', function()
{
alert($(this.attr("id")));
}
Or even
$(document).on('click', '.randomDiv', function()
{
alert($(this.attr("id")));
}
which bind event to the document level in DOM
Depending upon the version of jQuery you should use live, delegate, bind or on function.

If you append the element dynamically then the normal click function wont work. Use
$(document).on("click",".randomDiv",function(event){
alert($(this).attr("id"));
});

Related

Attach second click-event to an element after class name has been changed

I have a div with a class name a. I attach a click-event to this div like
$('.a').on('click', function() {
$(this).removeClass('a').addClass('b');
})
After this; element's class name changes from a to b. I want to attach second click event on .b like
$('.b').on('click', function() {
$(this).removeClass('b').addClass('c');
})
First click event works fine however second one does not fire. See my JSfiddle.
Attach the click even to a higher element in the DOM - when you change the class, the event bubbling up will change, e.g.
$("body").on("click", ".b", function() {
$(this).removeClass('b').addClass('c');
});
You can add the second event after the first one has fired:
$('.a').on('click', function() {
$(this).removeClass('a').addClass('b');
$('.b').on('click', function () { /* ... */ });
})
You're running the .b code at the beginning, when the element doesn't have class b. Try adding the new onClick handler in the code for your first onClick.
Code:
$('.a').on('click', function() {
$(this).removeClass('a').addClass('b');
$('.b').on('click', function() {
$(this).removeClass('b').addClass('c');
})
})
$(".a").click(function() {
$(this).removeClass("a").addClass("b");
$(".b").click(function() {
$(this).removeClass("b").addClass("c");
})
})

Click event is not working for dynamically changed class in jquery

I have two class .btnn and .sleep_avail sometimes i changes the css of a anchor from .btnn to .sleep_avail
Now i have two function for anchor click
$('.btnn').click(function () {
alert('yes btn');
});
And Second one is
$('.sleep_avail').click(function () {
alert('yes sleep');
});
Now when i click on the anchor with class sleep_avail which is changed dynamically from btnn class the event written for btnn raised and i get response accordingly. But what i need is that the event for sleep_avail should be raised. Kindly help.
Anytime, you use dynamically created tags, you must use
$(document).on('#event','#selector',function () {...});
so here
$(document).on('click','.sleep_avail',function () {...});
Because event handlers bind to the currently elements, they have to exist on the page when .on()is called
Here is the working DEMO http://jsfiddle.net/ARBdU/
$(document).on('click','.btnn, .sleep_avail',function () {
if($(this).hasClass('btnn'))
{
...
}
else if($(this).hasClass('sleep_avail'))
{
...
}
});
try
$(document).on('click','.sleep_avail',function () {

$(document).ready listeners not running on dynamic content

I have a $(document).ready function that sets up listeners for certain elements. However, all of the #leave-ride elements are added dynamically.
Listeners:
$(document).ready(function() {
$("#post-ride").click(function() {
addRide(currentDriver, $(destinationInput).val(), $(originInput).val(), $(dateInput).val(), $(timeInput).val());
$.getScript("scripts/myRides.js", function() {});
});
$("#request-ride").click(function() {
requestRide(currentDriver, $(destinationInput).val(), $(originInput).val(), $(dateInput).val(), $(timeInput).val());
$.getScript("scripts/myRides.js", function() {});
});
$("#leave-ride").click(function() {
console.log("leave Ride");
leaveRide(currentDriver, $("leave-ride").closest("div").attr("id"));
$.getScript("scripts/myRides.js", function() {});
});
});
What do I need to do to get that listener to listen to dynamic content?
Yes, ready runs only once. You can use event delegation:
Take the element closest to the #leave-ride which is not loaded dynamically (document in extreme cases). Then attach the handler on it, and use #leave-ride as the selector for the delegated event.
Assuming a div having the id #container is that static element:
$('div#container').on('click', '#leave-ride', function(){…});
See also Event binding on dynamically created elements?
Use on, change your event declaration
$("#post-ride").click(function() {
to
$("body").on('click',"#post-ride",(function() {
Use .on()
Example:
$("#leave-ride").on('click', function() {
console.log("leave Ride");
leaveRide(currentDriver, $("leave-ride").closest("div").attr("id"));
$.getScript("scripts/myRides.js", function() {
});
});

Toggling Classes Voids the Event function?

I thought this would work, but whenever I click on the element with the class name of one and it changes to the class named two, I can't get the second event to work. What am I missing here?
//first event
$('.one').on('click', function () {
$('.one').attr('class', 'two');
});
//second event
$('.two').on('click', function () {
$('.two').attr('class', 'one');
});
You need to delegate the event to a static parent..
The problem is , because you seem to dynamically change the class you need to bind the event every single time you change the class.. So delegating it should remove this problem..
Also You can write this as a Single event..
$('body').on('click','.one' , '.two', function() {
if( $(this).hasClass('one'){
function1();
}
else if( $(this).hasClass('two'){
function2();
}
$(this).toggleClass('one two');
});
Why not more simple :) http://jsfiddle.net/XZeNE/1/ or this http://jsfiddle.net/4mJJe/
use API - toggleClass
Further HTML CHange Dmeo http://jsfiddle.net/vuLQK/1/
code
$('.one').on('click', function() {
$(this).toggleClass('two');
});​
HTML change
$('.one').on('click', function() {
$(this).toggleClass(function(){
if($(this).hasClass('two'))
$(this).html('NOw its class two HTML HULK');
else
$(this).html('CLASS ONE HTML IRONMAN' );
return "two";
})
});
​
You should use .on to attach to one of the ancestors of the 2 elements and then use the selector argument to match the event target. The selectors won't match elements that aren't present when the handlers are bound.
$(function () {
$("#container").delegate(".one", "click", function () {
$(this).attr('class', 'two');
});
$("#container").delegate(".two", "click", function () {
$(this).attr('class', 'one');
});
})

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.
});

Categories