Javascript/jQuery Regular Expression code issue - javascript

I am working with jqDock on a DotNetNuke project. I ran jQuery.noConflict() and went through the jqDock.js file and changed all '$' to 'jQuery' (though I don't think it was necessary).
In this little bit of code I have an issue:
altImage : function(){
var alt = jQuery(this).attr('alt');
return (alt && alt.match(/\.(gif|jpg|jpeg|png)$/i)) ? alt : false;
} //end function altImage()
At the end of the regular expression there is a chunk that says $/i, My find/replace set this to jQuery. It broke the program. Is this because that '$' symbol isn't associated with jQuery there? Is it part of the Regular Expression? If so...what exactly is it saying?

The $ sign in this case is used as part of the regular expression, not as a call to jQuery, so that's why you had problems. It matches the end of the string that the regular expression is being performed on.

The $ matches the end of the string so it's not jQuery related here.
Some reading on regexp can be found here

The usual style to writing jQuery plugins would mean that one would not need to replace $ throughout the plugin. Most plugins are written such that the plugin code is surrounde by a self-invoking anonymous function that passes in jQuery for a parameter $ such that $ refers to the jQuery object inside of that function. Like so
(function($) {
// I can happily use $ here to refer to the jQuery object
$.fn.myFunction ....
})(jQuery);
So be careful when doing a naive find/replace.
As others have already mentioned, in the context of a regular expression, $ is used to match the end of the string.
Finally, when using $.noConflict(), you can assign the jQuery object to a different alias and use that alias throughout the subsequent code. For example
var $j = $.noConflict();
// can use $j alias for jquery now
$j(document).ready(function($) {
// can use $j or $ for jQuery object inside this function as the
// jQuery object is passed in
});

Be really careful when doing such huge find/replaces in your code. You changed the $ sign used in a regular expression to a jQuery expression, which is wrong. Every replace of this magnitude (replace everything in a document by other string) should be done wisely.
Read noConflict documentation to see which options do you have when using it - there's even one that let's you still use $ for jQuery.

Related

Adjusting jQuery to work on Wordpress (syntaxerror)

I have a line of code that has a "$" value in it, which Wordpress doesn't seem to accept. How to adjust the "$", so that Wordpress will read it correctly?
jQuery(document).bind('gform_post_render',function(){
jQuery('#input_24_4').change(function(){
jQuery('#input_24_3').data('amount',$(this).val());
});
});
$ should be an alias of jQuery, anyway, for some reason $ is not defined sometimes. You can fix it by using an anonymous function:
(function($) {
$(document).bind('gform_post_render',function() {
$('#input_24_4').change(function(){
$('#input_24_3').data('amount',$(this).val());
});
});
})(jQuery);
Also, make sure you've loaded jQuery library before embedding / executing this piece of code.
Where is this line of code? If it's part of a double-quoted string in any of your PHP files, you need to escape the $ with a backslash: \$
Apart from that, jQuery runs in noConflict mode in Wordpress. That means, it doesn't set the global $ variable, just the jQuery name.
If you want to change that, you need to set it yourself somewhere before this line:
window.$ = window.jQuery;

What does the command that start with '$.' do/mean in Javascript? This is NOT '$' selector to select an element [duplicate]

In the following JavaScript code there is a dollar ($) sign. What does it mean?
$(window).bind('load', function() {
$('img.protect').protectImage();
});
Your snippet of code looks like it's referencing methods from one of the popular JavaScript libraries (jQuery, ProtoType, mooTools, and so on).
There's nothing mysterious about the use of $ in JavaScript. $ is simply a valid JavaScript identifier. JavaScript allows upper- and lower-case letters (in a wide variety of scripts, not just English), numbers (but not at the first character), $, _, and others.¹
Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it. In that case you use jQuery instead of $. In fact, $ is just a shortcut for jQuery.
¹ For the first character of an identifier, JavaScript allows "...any Unicode code point with the Unicode property “ID_Start”..." plus $ and _; details in the specification. For subsequent characters in an identifier, it allows anything with ID_Continue (which includes _) and $ (and a couple of control characters for historical compatibility).
From another answer:
A little history
Remember, there is nothing inherently special about $. It is a variable name just like any other. In earlier days, people used to write code using document.getElementById. Because JavaScript is case-sensitive, it was normal to make a mistake while writing document.getElementById. Should I capital 'b' of 'by'? Should I capital 'i' of Id? You get the drift. Because functions are first-class citizens in JavaScript, you can always do this:
var $ = document.getElementById; //freedom from document.getElementById!
When Prototype library arrived, they named their function, which gets the DOM elements, as '$'. Almost all the JavaScript libraries copied this idea. Prototype also introduced a $$ function to select elements using CSS selector.
jQuery also adapted $ function but expanded to make it accept all kinds of 'selectors' to get the elements you want. Now, if you are already using Prototype in your project and wanted to include jQuery, you will be in problem as '$' could either refer to Prototype's implementation OR jQuery's implementation. That's why jQuery has the option of noConflict so that you can include jQuery in your project which uses Prototype and slowly migrate your code. I think this was a brilliant move on John's part! :)
That is most likely jQuery code (more precisely, JavaScript using the jQuery library).
The $ represents the jQuery Function, and is actually a shorthand alias for jQuery. (Unlike in most languages, the $ symbol is not reserved, and may be used as a variable name.) It is typically used as a selector (i.e. a function that returns a set of elements found in the DOM).
As all the other answers say; it can be almost anything but is usually "JQuery".
However, in ES6 it is a string interpolation operator in a template "literal" eg.
var s = "new" ; // you can put whatever you think appropriate here.
var s2 = `There are so many ${s} ideas these days !!` ; //back-ticks not quotes
console.log(s2) ;
result:
There are so many new ideas these days !!
The $() is the shorthand version of jQuery() used in the jQuery Library.
In addition to the above answers, $ has no special meaning in javascript,it is free to be used in object naming. In jQuery, it is simply used as an alias for the jQuery object and jQuery() function.
However, you may encounter situations where you want to use it in conjunction with another JS library that also uses $, which would result a naming conflict. There is a method in JQuery just for this reason, jQuery.noConflict().
Here is a sample from jQuery doc's:
<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
// Code that uses other library's $ can follow here.
</script>
Alternatively, you can also use a like this
(function ($) {
// Code in which we know exactly what the meaning of $ is
} (jQuery));
Ref:https://api.jquery.com/jquery.noconflict/
From the jQuery documentation describing the jQuery Core Object:
Many developers prefix a $ to the name of variables that contain jQuery
objects in order to help differentiate. There is nothing magic about
this practice – it just helps some people keep track of what different
variables contain.
Basic syntax is: $(selector).action()
A dollar sign to define jQuery A (selector) to "query (or find)" HTML elements A jQuery action() to be performed on the element(s)

Declaring variables javascript [duplicate]

This question already has answers here:
Why would a JavaScript variable start with a dollar sign? [duplicate]
(16 answers)
Closed 9 years ago.
I just have a quick question and cant find anything on google. I was going through some code another programmer put together and he declares ALL of his javascript variables with $ in front of them...for instance:
var $secondary;
Is there a reason for this? Could this cause problems in the future if JQuery ever ends up being used. I'm just curious because I was going to clean it up if so.
Is there a reason for this?
Hard to say. Maybe he came from a PHP background where $ prefixes the variables. Maybe he's a jQuery addict. Who knows? You'd have to ask him. That aside, $ is a perfectly legitimate character to use in a JavaScript variable name but as you noted, it could cause issues with jQuery. But that's why jQuery offers a noConflict() option.
I use this convention too keep track of if a variable is storing a JQuery object. So say the function getJQueryObject() returns a JQuery object and I want to store it.
i.e:
var $myJQobj = getJQueryObject();
Makes it clear that $myJQobj is a JQuery object unlike i.e
var myStr = "hello";
The $ as the first character in the identifier doesn't have any special meaning, you aren't invoking a method like $(), it's just a perfectly valid identifier in JavaScript. But the factthat the $ is used in JQuery makes what I was talking about before even clearer.
$ is a valid variable character, and in PHP all variables start with it. It's possibe that that particular developer uses $ as a "flag" to mean "this is a variable". It has no special meaning.
$ just a character that you can use in a variable name. Some people like to use it to denote variables that contain jQuery objects:
var $foo = $('#foo');
var bar = 42;
But that's just a personal preference. It has no special meaning.
its just a convention for jQuery DOM selctions.
var $logo = $('a.logo');
it wont cause any issues - it just lets other devs know that you're working with a jQuery wrapped dom element.
$ is fine for use in JavaScript. PHP uses the same variable syntax so maybe he was used to it from that.

$ae. javascript notation

I am starting to learn jQuery. Looking though the MVC3 project that makes use of Awesome MVC Html helpers, I have stumbled upon a javasript code that I don't know how to understand yet:
$ae.autocomplete('Requestor'
What is $ae is calling a jQuery autocomplete on in this case? ae isn't an element, so this isn't an id or class selector.
P.S. And while you are at it, please let me know what $. as in $.getJSON calls getJSON on?
Assuming that there isn't a typo, $ae is a variable. Since $ is just a javascript function you can assign the result of it to a variable, $ae = $("#myid"). While I don't know that $ae is definitely the result of that, the naming convention ($ at the beginning) makes me suspect that it is.
In jQuery, the $ is a convenient alias for the jQuery object. So $.getJSON() is calling the getJSON() method of the jQuery object. This is pretty confusing at first, but once you get used to it it's nice and concise.
It seems like common practice in jQuery development to use a $ to prefix variables that result from selecting things with jQuery, like this:
var $myList = $('.list-item');
The $ is a legal character to use in variable names, so I guess it's a reminder that the object contains a jQuery wrapped set. It's a good idea to assign the results of your selections to variables if you'll use the selected items again; otherwise you're wasting resources.
In your example, the $ae is the equivalent of something like this:
$('#my-input').autocomplete('Requestor ...

$ vs. jQuery: Which should I use?

What is the diffrence between them? Which is better?
$ is an alias for jQuery, neither is "better" really, jQuery is provided in case something else is using $, like Prototype (or jQuery.noConflict() was called for another reason...).
I prefer $ for brevity because I know it refers to jQuery, if you're unsure (like when writing a plugin) use jQuery for your primary reference, for example:
(function($) {
//inside here $ means jQuery
})(jQuery);
The functionality is identical if there is no conflict.
Use 'jQuery' instead of '$' to be especially explicit/descriptive, or if you currently use or anticipate using another library that defines '$'.
See also http://api.jquery.com/jQuery.noConflict/
jQuery == $ == window.jQuery == window.$
jQuery and $ are defined in window, and $ can be used if no other library is making use of it, thus creating conflicts.
Either use jQuery.noConflict() or closures:
(function ($) {
// code with $ here
})(jQuery)

Categories