Question

I want this webpage to highlight certain elements when you click on one of them, but if you click anywhere else on the page, then all of these elements should no longer be highlighted.

I accomplished this task by the following, and it works just fine except for one thing (described below):

$(document).click(function() {
    // Do stuff when clicking anywhere but on elements of class suggestion_box
    $(".suggestion_box").css('background-color', '#FFFFFF');
});
$(".suggestion_box").click(function() { 
    // means you clicked on an object belonging to class suggestion_box
    return false;
});

// the code for handling onclicks for each element
function clickSuggestion() {
    // remove all highlighting
    $(".suggestion_box").css('background-color', '#FFFFFF');
    // then highlight only a specific item
    $("div[name=" + arguments[0] + "]").css('background-color', '#CCFFCC');     
}

This way of enforcing the highlighting of elements works fine until I add more html to the page without having a new page load. This is done by .append() and .prepend()

What I suspected from debugging was that the page is not "aware" of the new elements that were added to the page dynamically. Despite the new, dynamically added elements having the appropriate class names/IDs/names/onclicks ect, they never get highlighted like the rest of the elements (which continue to work fine the entire time).

I was wondering if a possible reason for why my approach does not work for the dynamically added content is that the page is not able to recognize the elements that were not present during the pageload. And if this is a possibility, then is there a way to reconcile this without a pageload?

If this line of reasoning is wrong, then the code I have above is probably not enough to show what's wrong with my webpage. But I'm really just interested in whether or not this line of thought is a possibility.

Was it helpful?

Solution

Use .live to "Attach a handler to the event for all elements which match the current selector, now and in the future". Example:

$(".suggestion_box").live("click", function() { 
    // means you clicked on an object belonging to className
    return false;
});

Also see .delegate, which is similar.

OTHER TIPS

Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by .delegate() will always propagate to the element to which they are delegated; event handlers on any elements below it will already have been executed by the time the delegated event handler is called.

from the jQuery documentation =)

(only to explain better why @karim79 also suggested the delegate method ;P )

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top