John Smith
John Smith

Reputation: 6259

Cannot change color of a-tag

My demo code: http://jsfiddle.net/4w3Hy/3/

My first code adds html to an div with the id:Content:

$(".text").click(function() {
 $("#Content").html($(this).next(".text1").html());
});

On the id:Content, with the new html, i try to run another jquery function:

$(".click").click(function() {
 $('.click').css('color','');
 $(this).css( "color", "red" );
});

But somehow this wont work!! What did i made wrong? to see html http://jsfiddle.net/4w3Hy/3/

Upvotes: 1

Views: 55

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

Use on to attach events to elements dynamically appended to the DOM. In the original code the .click element is not present on the DOM at the time the click event handler is attached to all elements with the class .click, therefore the event is never bound to the new element.

Using on() allows us to attach the event handler to a parent such as the document already available on the DOM. .click elements are then appended to the document and when clicked fire a click event that propagates to the document. Once the document receives the click event it will determine if the event was fired by an element with class .click, if so it will execute our attached event. If you are familiar with the deprecated live() method, you pretty much understand the concept.

Normally, it would be best to attach to a static parent closer to the .click element, however since I did not have your entire HTML markup, I used document.

$(".text").click(function() {
    $("#Content").html($(this).next(".text1").html()); });

$(document).on("click", ".click", function() {
    $('.click').css('color','');
    $(this).css( "color", "red" ); });

JS Fiddle: http://jsfiddle.net/4w3Hy/5/

Upvotes: 2

sangram parmar
sangram parmar

Reputation: 8736

Try this:

DEMO

$(".text").click(function() {
    $("#Content").html($(this).next(".text1").html());
    $(".click").click(function() {

    $(this).css( {color:"red" });
});
});

Upvotes: -1

Related Questions