How method chaining works in this case in JQuery

59 Views Asked by At

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

There are 1 best solutions below

0
On

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>