Can someone explain how the following js syntax works?
Is this a function?
Why is the syntax like this?
How does it work (accessed)?

SomeName(function()
{
	otherFunction();
	
	var form = document.forms.passengerInformation;
	
    
    toggleCreateProfileFields();
	SomeName("#createUserProfileCheckbox").click(function() {
		toggleCreateProfileFields();
	});
});

Dani AI

Generated

This is not a mysterious new language — it’s jQuery being used via an alias. was right to suspect a JS library, and correctly tracked down the cause: the author released the usual $ alias and kept a different name for jQuery. In JavaScript functions are first-class values, so calling the jQuery function with a function argument registers that function to run when the DOM is ready. Calling it with a selector string returns a collection you can call methods on (attach events, manipulate DOM, etc.).

Key points: passing a function to jQuery is shorthand for “run this on DOM ready”; passing a string (selector) returns matched elements; methods such as .click() attach handlers (modern code prefers .on()). Using noConflict() hands $ back to whatever library owned it, so the returned jQuery reference is used instead. Because the ready wrapper runs after the DOM exists, plain DOM accesses (for example document.forms[...]) are safe inside it.

A simple, safe pattern to avoid global-$ conflicts is to create a local $ inside a closure and pass in the jQuery object:

(function($) {
  $(function() {
    $('#myCheckbox').on('click', function() {
      toggleFields();
    });
  });
})(jQuery);

If you used noConflict(true) and removed the global jQuery, pass your saved alias into the IIFE instead.

For more detail and edge cases see the jQuery docs on noConflict and the jQuery function/ready shorthand, and read about function values on MDN:

Troubleshooting checklist: confirm jQuery is loaded before your code, ensure the alias is created before use, watch the console for errors, and prefer .on() for event binding in modern code.

Recommended Answers

All 2 Replies

Looks a little like jquery or some other Javascript library is being used.
Libraries like jquery make javascript so much easier to use.

Instead of writing getElementById("createuserprofilecheckbox")
in jquery you'd write $("#createuserprofilecheckbox")

I'm guessing the above function may have been written for a different library, personally i'm only familiary with jquery.

Yes! I think you are correct! Thanks! I just found this bit of code, so I think my function is an extension of jQuery.

var SomeName=jQuery.noConflict();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.