-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
  • 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. Commented Dec 10, 2022 at 14:15

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

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.