Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery click anywhere except certain divs and issues with dynamically added html

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.

like image 678
jCuga Avatar asked Mar 22 '26 05:03

jCuga


1 Answers

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.

like image 66
karim79 Avatar answered Mar 23 '26 19:03

karim79