Which is the difference between:
jQuery(selector).change(function(){
//something
}).change();
And this:
jQuery(selector).change (function(){
//define your code here to execute once the change event is happened.
});
Thanks in advance!
I could not find an explanation about difference between those methods, that is why I ask here.
The first adds a change event listener to jQuery(selector)
and then triggers it, causing the function to fire even without the change event occurring.
Notice how the log appears when running the snippet below, even without changing the text input:
jQuery("#text").change(function(){
console.log("I changed");
}).change();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<input type="text" placeholder="Example" id="text" />
Note that .change()
is deprecated, the equivalent of the above is to use .on("change", handler)
, followed by trigger()
(see the .on()
docs):
jQuery("#text").on("change", function(){
console.log("I changed");
}).trigger("change");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<input type="text" placeholder="Example" id="text" />
The second just adds a change event listener, and doesn't manually trigger the change event:
jQuery("#text").change(function(){
console.log("I changed");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<input type="text" placeholder="Example" id="text" />