Maghawry Hussein
Maghawry Hussein

Reputation: 1

How method chaining works in this case in JQuery

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.

Upvotes: -2

Views: 49

Answers (1)

Aniket Panchal
Aniket Panchal

Reputation: 166

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>

Upvotes: 0

Related Questions