dnccc12333
dnccc12333

Reputation: 79

Jquery .click() not working

The problem with .click() is that I have this code:

$(".masteries").click(function()
{
    $(".masteries").css("background-color","red");
});

And when I click on a div with class "masteries" nothing happens, though If I click on div with this code:

$("body").click(function()
{
    $(".masteries").click(function()
    {
        $(".masteries").css("background-color","red");
    });
});

Everything works just fine. What COULD be the problem?

Upvotes: 0

Views: 50

Answers (2)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93631

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 :)

Upvotes: 0

PeterKA
PeterKA

Reputation: 24648

If your .masteries elements are created after the page is loaded (DOM ready), then use event delegation:

$(document).on('click', '.masteries', function() {
    $(this).css("background-color","red");
});

If the .masteries elements do exist at DOM ready event, then use the following:

$(document).ready(function() {
    $(".masteries").on('click', function() {
       $(this).css("background-color","red");
    });
});

Upvotes: 1

Related Questions