views:

66

answers:

2

What im trying to do is when the p inherits the class "active" that div.test will print the link rel correctly.

Currently if the page loads without the class assigned to the p tag, it will not. How can I make it happen when the p tag inherits the class "active" the link printed in div.test will get the rel printed correctly?

$(document).ready(function(){
 var relvar = $('p.active').attr('rel');
 $("div.test").html("<a rel='"+ relvar +"'>hello</a>");

 $("p").click(function () {
 $(this).toggleClass("active");
 });

 });
+2  A: 

I am not sure what you asking. Are you saying that you would like this code:

var relvar = $('p.active').attr('rel');
$("div.test").html("<a rel='"+ relvar +"'>hello</a>");

To be run whenever the <p> element changes classes? If so, there is no "onchangeclass" event or anything like that, but you could actually create your own event to handle this:

$('p').bind('toggleActive', function() {
    if($(this).hasClass('active')) {
        var relvar = $(this).attr('rel');
        $("div.test").html("<a rel='"+ relvar +"'>hello</a>");        
    }
}).click(function() {
    $(this).toggleClass('active').trigger('toggleActive');
});

Check this code in action.

This is actually kind of roundabout - it would be simplest to just do the logic in the click handler itself. The main advantage of moving it to its own event is that if you then need to do this elsewhere in the code you can keep that logic separate and just "trigger" it as you need.

Paolo Bergantino
Beat me to it. The "DOMAttrModified" event would work, but it's only supported by Firefox and Opera.
Ben Blank
This looks great, this is exactly what I was looking for. Thank you so much!
Bruno
A: 

Not quite sure if this is what you are going for, but can you not handle it in the click code?

$(document).ready(function() {
  $('p').click(function() {
    $(this).toggleClass('active');

    if ($(this).hasClass('active')) {
      relvar = $(this).attr('rel');

      $('div.test').html("<a rel='" + relvar + "'>hello</a>");
    } else {
      $('div.test').html("<a>hello</a>");
    }
  });
});

As far as I know, you will have to bind to some event in order for it to check and see if it needs to update the div.

Topher Fangio