Sunny Singh
Sunny Singh

Reputation: 127

conditional on off event binding in jquery

I am trying to bind on off event of a button using jQuery.

On very first time(when document loaded completely) I have to click the button twice to see the effacts.

Also p tag's click is not working.

    <p>Click the button below</p>
    <button class="blue">Remove the click event handler</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
        function changeColor(evt) {
            $('p').css("background-color", $(evt.target).attr('class'));
            $(evt.target).removeAttr('class').attr('class', 'pink');
        }
        $("button").click(function () {
            if ($(this).hasClass('pink')) {
                $(this).off("click", changeColor);
            }
            else {
                $(this).on("click", changeColor);
            }
        });
        $("p").on("click", function () {
            $('button').removeAttr('class').attr('class', 'green').on("click", changeColor);
        });
    </script>

Upvotes: 0

Views: 1147

Answers (1)

Satpal
Satpal

Reputation: 133453

I would recommend, you to use Event Delegation approach, when manipulation selector i.e. removing and adding classes.

$(document).on('click', "button:not(.pink)", changeColor)

In place of document you should use closest static container.

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

$(document).on('click', "button:not(.pink)", function() {
  $(this).removeClass().addClass('pink');
  console.log('Clicked')
})
.blue {
  background-color: blue;
}

.pink {
  background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button class="blue">Remove the click event handler</button>
<button class="blue">Remove the click event handler</button>


To fire event programmatically you need to use .trigger()

$('button').removeClass().addClass('green').trigger('click');

Upvotes: 2

Related Questions