-2

method chaining requires every method to return the jquery object but,
when we use: $("div").click(function(){ //some code }).css("backgroundColor","blue").

how does the css method get executed without clicking the div? how does it know the jquery object without click event gets triggered.

  • 1
    The `.click()` method, like any other jQuery methods, simply returns the jQuery object, and does not conditionally fire whatever that is chained after it based on the click event. That's why. In fact, if you swap the order around `.css().click()` it does exactly the same thing. – Terry Dec 10 '22 at 14:15

1 Answers1

0

Here chaining will work like $("div").css("backgroundColor","blue").click(function(){ //some code });

Below is the working code snippet for the same.

$(document).ready(function() {
    $("div")
    .css("background", "blue")
    .click(function() {
        alert('Clicked');
    });
});
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<div>Click Here</div>