user1978654
user1978654

Reputation: 25

Can i use events as an if statement condition

is it possible to use events as conditions ? and what if i want to say do this when the event on table cell is onclick :

if($(this).bind(onclick)){}

is this correct ?

Upvotes: 0

Views: 624

Answers (2)

Lyn Headley
Lyn Headley

Reputation: 11588

It is legal javascript, but not very useful. It will never do anything because the body of the if statement is empty. In addition, because .bind() returns the jQuery object, the condition will always be true. So although the javascript is legal and in that sense "correct", it is not very useful for anything.

Upvotes: 0

Anthony Grist
Anthony Grist

Reputation: 38345

Events are triggered when something occurs. If you click on a table cell, then a click event is triggered. You can't use them as conditions in if statements, but if you want to do something when a certain event happens, that's what an event handler is for.

As an example, this would bind an event handler for the click event to all table cells (<td> elements) present when the code is executed (on DOM ready):

$(document).ready(function() {
    $('td').on('click', function(e) {
        console.log('table cell clicked');
    });
});

Upvotes: 2

Related Questions