If you are loading elements dynamically, you can use a delegated event handler instead, attached to a non-changing ancestor of the changing elements:
$(document).on('click', '.masteries', function() {
$(".masteries").css("background-color","red");
});
This works by listening for the event (e.g. click) to bubble up to the ancestor element, then applies the jQuery selector to any elements in the bubble-chain, then applies the function only to any matching elements that caused the event. This means the elements only have to exist at event time and not event registration time.
Use document
as your default, and not 'body'
as 'body'
has a nasty bug (if styling causes a calculated body height of 0 it gets no mouse events bubbled to it!)
Previous suggestion below:
That behavior sounds like you are just missing a DOM ready handler, but without a complete example this is only a guess. body
does exist at all times, but .masteries
only matches if your code follows the elements in the page.
$(function(){
$(".masteries").click(function()
{
$(".masteries").css("background-color","red");
});
});
Notes:
$(function(){...});
is just a shortcut for $(document).ready(function(){});
- Your second example registers a additional click event every time you click on the page. This is to be avoided :)