tags:

views:

41

answers:

2

My div has no id . can i call a jquery function on click of that div

div identified by class used in div.

<div class="divclass">

how can i call

$('.divclass').click(

???

+3  A: 

Here is the correct syntax:

$('.divclass').click(function(){
  alert('I got clicked !');
});

To trigger a click on the div programatically, you can do:

$('.divclass').click();

See:

Sarfraz
+3  A: 

To assign a click handler, you can do this:

$('div.divclass').click(function() {
    alert('i was clicked');
});

...or this, which is the same thing:

$('div.divclass').bind('click', function() {
    alert('i was clicked');
});

Here's an example: http://jsfiddle.net/MAKHh/


EDIT:

As noted by @mcgrailm, there's another means of firing code on the click of an element called .live(). As well as a related one called .delegate().

With live(), the handler will fire regardless of when the element is added to the page.

$('div.divclass').live('click', function() {
    alert('i was clicked');
});

Or with .delegate() you call it agains a container, and elements added to that container at any time will fire the handler.

$('.someContainer').delegate('div.divclass', 'click', function() {
    alert('i was clicked');
});

Or if you wanted to .trigger() a click event, do this:

$('div.divclass').click();

Or this:

$('div.divclass').trigger('click');

You can also call the handler without triggering the event.

$('div.divclass').triggerHandler('click');
patrick dw
don't forget live
mcgrailm
@mcgrailm - Good point. That and `.delegate()` as well. I'll update.
patrick dw
i am sure these things will work fine.
zod
Am asking a doubt or nonsense i dont know ..there are situations the div wil have 2 class.. or one class inside other consider situation <div class="divclass subclass" > . Now what i have to do?
zod
@zod - Are you saying you only want to attach the `click` handler if *both* classes are present? If so, do `$('div.divclass.subclass').click(...`.
patrick dw