August 17, 2013

Cannot change color of a-tag

John Smith’s Question:

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/

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/

It is because since the element is added dynamically it cannot be found by the running script. You have to use event delegation.

Try this

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!