Warface
Warface

Reputation: 5119

Check if element is clicked or hasClass

I was wondering if it's possible in jQuery to know if an element is clicked or hasClass()

This is what I've tried without success

if($('.subCat span[data-value="all"]').hasClass('checked') || $('.subCat span[data-value="all"]').click()){
        alert('woohoo');
    }

So how can I achieve this? I need to script to be executed when clicked or if it has the required class.

Thanks

Upvotes: 3

Views: 2353

Answers (3)

Gromer
Gromer

Reputation: 9931

If you need the function to run on click as well as initially for the elements with the checked class, I would suggest this:

function doStuff() {
    alert('woohoo');
}

$(document).ready(function() {
    // This will wire up a click event. When the matching elements are clicked,
    // the doStuff function will run.
    $('.subCat span[data-value="all"]').click(doStuff);

    // This will call the doStuff function for every matched element on the
    // document ready.
    $.each($('.subCat span[data-value="all"].checked'), function(index, value) {
        doStuff();
    });
});

Upvotes: 1

epascarello
epascarello

Reputation: 207501

To tell if it is clicked, you need to add an event handler

$(document).on("click",'.subCat span[data-value="all"]', function(){
    alert("I was clicked");
});

There are no events to tell you if it was a required class. If you want to check when the page is loaded, you can do it than.

$( function() {
    $('.subCat span[data-value="all"]').filter('.checked').each( function(){
        alert("I have a checked class at ready");
    });
});

Upvotes: 1

Kevin B
Kevin B

Reputation: 95020

What you need is a click event, not an if statement.

$('.subCat').on("click", 'span[data-value="all"].checked', function(){
    alert("woohoo foobar");
});

Upvotes: 2

Related Questions