0

I have a full AJAX page with elements that act like buttons with events like

onclick="$('#workcont').load('pages/mypage.html #m3-to-12');"

The elements being referenced are <li> and <tr> (in a table).

How do I attach event handlers to add the class selected on click?

1
  • Thanks. Adding class works very good, but nothing chenge visually! Why this may be? I make class .selected in css file with border adding. Commented Aug 30, 2011 at 16:13

4 Answers 4

1

If your page is loaded via AJAX you should attach your events with live, so if you want to attach a click event you can do it this way:

$("li, tr").live('click', function() {
  $(this).addClass("selected");
});

Update

The live() method was deprecated in jQuery version 1.7, and removed in version 1.9 . Use the on() method instead.

$("li, tr").on("click",function(){
    $(this).addClass("selected");
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can keep the inline onclick events and can also add additional click handler on those elements using jQuery. Try this

$("li tr").click(function(){
   $(this).addClass("selected");
});

Comments

1

Won't

 $('#workcont').load('pages/mypage.html #m3-to-12').addClass('selected');

work also?

Or are you trying to add the class to a different element?

It is a different element. If the element is loaded because of the load() use the callback parameter:

$('#workcont').load('pages/mypage.html #m3-to-12', function() { $('li').addClass('selected'); });

1 Comment

Very good example! But it's add class to loaded div with id #workcont, not to clickable element (li). How to fix it?
1

If you want the element to be selected as soon as it is clicked use this:

$("li, tr").click(function() {
          $("li, tr").removeClass("selected");//To Remove any previuosly selected elements
          $('#workcont').load('pages/mypage.html #m3-to-12'); 
          $(this).addClass("selected");// Select the clicked element
        });

If you want the element to be selected as soon as the AJAX page is loaded use this:

$("li, tr").click(function() {
          $("li, tr").removeClass("selected");//To Remove any previuosly selected elements
          $(this).addClass("some_temp_unique_class_name");
          $('#workcont').load('pages/mypage.html #m3-to-12', function(response, status, xhr) {
              if (status == "success") {
                var elem = $("li.some_temp_unique_class_name,tr.some_temp_unique_class_name");
                elem.removeClass("some_temp_unique_class_name").addClass("selected");// Select the clicked element
              }
            }); 
        });

Refer .load() for more details

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.