3

I'd like to know if it is possible to detect if an element is not clicked. This is the code I have:

$("#mpElement").myFeature({
            .........
            .........
            .........
    afterDo: function() {
        // This if-else statement has to go inside "when not clicked" condition. 
        // Not sure how to do this...
        if($(".myButton").last().hasClass("selected")) {
            $(".myButton").first().addClass("selected");
            $(".myButton").last().removeClass("selected");
        } else {
            $(".selected").removeClass("selected").next().addClass("selected");
        }
        $(".myButton").on("click", function(){
            $(".myButton").removeClass("selected");
            $(this).closest(".myButton").addClass("selected"); 
        });
    }
});

You will notice $(".myButton").on("click", function(){ for detecting click event. I'd like to put the if-else statements above this function inside when not clicked condition. Not sure how to do this.

user1448031
  • 2,172
  • 11
  • 44
  • 89
  • _"detect if an element is not clicked"_ - Do you mean to test if an element has never been clicked? Or hasn't been clicked since some other event? There's no "user thought about clicking but then changed their mind" event... – nnnnnn Sep 16 '12 at 08:26

1 Answers1

12

You can maintain a data property to that element as a click detector.

Example:

<button class="myButton" data-clicked="no">My Button</button>

Here, I set data-clicked=no as initial config.

Within the click event set data-clicked to yes like:

$('.myButton').on('click', function() {
  $(this).data('clicked', 'yes');
});

Now check this data-clicked property like below:

var isClicked = $('.myButton').data('clicked');

if( isClicked == 'yes') {
   // do something
} else {
  // do something else
}
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
  • 3
    Setting a flag is a good plan. But you don't need the initial `data-clicked` attribute. You can just say `$(this).data('clicked',true)` and then later `if ($(this).data('clicked'))...` – nnnnnn Sep 16 '12 at 08:29
  • This doesn't create an actual `data-clicked` attribute. If you need to create the attribute, use .attr(): `$(this).attr('data-clicked', 'true');` – Alen Simonyan Jan 15 '20 at 14:03