1

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
  • Can the "active" class be assigned any way other than by clicking on the p element? Commented Jun 10, 2009 at 23:04
  • 1
    Hey thanks. Yeah I just found this site today, pretty awesome. Thanks again. Commented Jun 11, 2009 at 2:44

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Beat me to it. The "DOMAttrModified" event would work, but it's only supported by Firefox and Opera.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.