2

I want to trigger a function when has an specific class, in this case Clicked so I want to return the alert (unliked)

HTML

<div class="social">
<div class="LikePost default"></div>
</div>

JQUERY

$(".social").find(".LikePost").trigger("click"); /*when has class "clicked"*/
alert("unliked")

TRIGGERED FUNCTION

$('.LikePost').on('click', function() {
  if ($(this).hasClass("default")) {
    $(this).addClass("Clicked");
    $(this).removeClass("default");
    alert("post liked");
  } else {
    $(this).addClass("default");
    $(this).removeClass("Clicked");
    alert("post unliked");
  }
});
2
  • 3
    $(".clicked").trigger("click") ? Commented Mar 20, 2018 at 20:17
  • small, quick and awesome!! Commented Mar 20, 2018 at 20:20

2 Answers 2

2

Alright x-D

$(".Clicked").trigger("click")
Sign up to request clarification or add additional context in comments.

Comments

1

You can rewrite your trigger like this:

$('.LikePost').on('click', function(){

// just invert classes state
$(this).toggleClass("default");
$(this).toggleClass("Clicked");

// if is default, its liked, if not, its not liked
if($(this).hasClass("default")) {
    alert("post liked");
} else {
    alert("post unliked");
}
});

And if you want to manually trigger all liked posts, just do it:

$('.Clicked').trigger('click');

4 Comments

Awesome arrangement. but does toggleClass deletes the prior class and adds the new one? or just add both classes to the element and uses the selected between parenthesis?
toggle will add if it's not there, and remove if it's there so the first time you click it, it will remove default and add Clicked, next time will add default and remove Clicked and so on
that would be the same? $(this).toggleClass("default, Clicked");
almost, you can do it this way: $(this).toggleClass("default Clicked");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.