Replacing $ for jQuery - .addClass method - javascript

I'm having an issue trying to fix a conflict between both libraries and have used the noConflict in some sections, however I keep getting the $active is null error
I'm specialized in server-side scripting and not in Javascript (nor have time to read some documentation) so would appreciate any help.
Here is my code:
First (I'm just guessing here) jQuery adds a class which will be used later
jQuery(".paging a:first").addClass("active");
Now, it's time to use that class
var triggerID = $active.attr("rel") - 1; //Get number of times to slide
Since the code is for a slider the error appears every time this line is reached so my question is... Is there any way I can remove the $ and still use jQuery in that line?
P.S: I'm using jQuery 1.6.1 min and MooTools 1.2 although I doubt this is relevant I know they have conflicts so probably the source of this error.

To select an element by it's class in jQuery you need to use CSS style notation in a jQuery object, which in your example would be jQuery(".active"). Try this:
var triggerID = jQuery(".active").attr("rel") - 1; //Get number of times to slide
To use your original code, you'd need to assign the $active variable to be the jQuery object containing the element, like this:
var $active = jQuery(".paging a:first").addClass("active");
var triggerID = $active.attr("rel") - 1; // This will now work, assuming it's in the same scope as the above.

$active has nothing to do with jQuery in this case (though it might be a jQuery variable). In javascript you can name variables "$something" without a problem, and it doesn't collide with something named simply "$", which is another variable-name altogether. It's like saying you have removed all references to the variable "car", but don't understand why you get an error complaining about the lack of a "carpet". They're totally independent, thus the code you have posted is insufficient to see what is wrong.
[Edit]
If this sounded harsh in some way it's just me having a problem formulating myself in an understanding way on this matter, as I was simply trying to educate, not implying that this is something that you should know. It's an error a lot of peoples do in javascript (at least several I know of).

It should just be a matter of replacing $ with jQuery wherever you would normally use $.
So, instead of the typical:
$('.active').attr('rel')
use:
jQuery('.active').attr('rel')

$active is a javascript variable (they chose to put the $ in front of it to help them remember it stores a jQuery object, but the behavior is the same).
So, replacing every instance of $active by active should still work. I don't know ifit will solve your problem though.
One other thing you should try is putting your code in a closure:
(function($){
// your code
})(jQuery);
That way, inside of the closure, $ will only reference jQuery

Related

Caching jQuery variables

I just read that if you are referring to the same DOM element over and over in a function it is better to cache them in a local variable like :
var btn = $('#clearBtn');
I have followed this where necessary but when accessing back this object I have always used $(btn).somemethod(); although we can access this directly like btn.somemethod();
I just need to know whether this will have a negative impact ?
There's no point in passing the jQuery object through the jQuery constructor. It's just wasteful. If the dollar sign looks nice to you, just prepend it to the variable name and use $btn in place of $(btn):
var $btn = $('#clearBtn');
btn.somemethod(); will work, and is the correct way, since btn is already a jQuery object.
Besides, unless you call $('#clearBtn'); a lot of times in a short period of time, I wouldn't bother caching it.

Control references in jQuery

function eegetdropdownvalue_str(ctl){return ctl.selectedIndex>=0&&ctl[ctl.selectedIndex]?ctl[ctl.selectedIndex].value:''}
The above function is called with
co.p1A10=eegetdropdownvalue_str(document.formc.p1A10);
I want to switch the call over to jQuery to drop the document.form reference however doing this
co.p1A10=eegetdropdownvalue_str($('p1A10'));
Does not reference the control correctly - How should I do this?
There's two things wrong with your code.
First, $('p1A10') references nothing.
jQuery selectors work almost identically (if not completely identically) to the way css works.
So, just ask yourself how you would reference the object(s) in question in CSS and you're half way there.
I'm assuming that p1A10 is the name or id of an object. Since we're using CSS/jQuery syntax, this should be an id, although you can select by other attributes such as $("select[name='p1A10']") .
To reference an object by ID we use the # character (again, just like in CSS). So we can select your node via $('#p1A10').
The second problem is that your function is expecting a DOM object not a jQuery object. To keep your code intact, we need to say $('#p1A10')[0] where 0 is the first element within the collection of jQuery elements.
I've provided two examples to explain this a little better. One uses your existing infrastructure and one replaces it.
http://jsfiddle.net/TD6Uu/5/
Hope it helps.
Given a form with id formc and a select with name p1A10 you could e.g. use:
o.p1A10 = eegetdropdownvalue_str($('#formc select[name="p1A10"]').get(0));
If this doesn't do it, please provide use with the exact HTML structure

Javascript override problem class xml

Not sure what is the problem , this the second post looking for the answer.. but this time with a with the example .
What i'm doing : I 'm implementing a gallery that is getting a xml, and then build me using some javascript code. the problem i tried to call twice gallery.init like :
$(document).ready(function(){
galleryXML.init({
id: "#gallery1"
});
galleryXML.init({
id: "#gallery"
});
})
I expected to have one in #gallery1 other in #gallery. Can someone tell me what the problem(it only happen when i had the loadXml() , so probably something with asynchronous call not sure )?
I think your problem can be that you are using the same variable _P for (what you expect to be) 2 different instances of the galleryXML.
The _P variable is created and initialized when the javascript code is parsed, because of the () after the var galleryXML = function() {...}.
So I guess your problem is going to be solved if you just put the variable inside the init of galleryXML. You can see the code here: jsfiddle.net/rpNab/3/ (notice that now each li is inside each gallery, instead of both li in the last gallery)
EDIT: And I realize that now with my modification the galleryXML module seems ugly (because it only has one method and no variables), so I made a minor refactoring in order to have more methods inside that class, but the methods now must receive the parameter because the class itself continue to be "static", but the parameters can make it act for different contexts. Hope it helps: jsfiddle.net/rpNab/4/

Most efficient way to re-use jQuery-selected elements

I can imagine the correct answer to this based on theory, but I'm just looking for some confirmation. I'm wondering what the most efficient way to re-use a jQuery-selected element is. For example:
$('#my_div').css('background','red');
//some other code
$('#my_div').attr('name','Red Div');
vs.
myDiv = $('#my_div');
myDiv.css('background','red');
//some other code
myDiv.attr('name','Red Div');
I assume the second example is more efficient because the element #my_div doesn't have to get found more than once. Is that correct?
Similarly, is it more efficient to first save $(this) in a varaible, such as 'obj', and then reuse 'obj' rather than using $(this) over and over? In this case, jQuery isn't being forced to find an element over and over again, but it IS being forced to convert this to a jQuery object [$(this)]. So as a general rule of thumb, should a jQuery object ALWAYS be stored in a variable if it will be used more than once?
You should write your code such that you limit the number of DOM traversals.
When you write something like this:
$('#my_div').css('background','red');
//some other code
$('#my_div').attr('name','Red Div');
You are finding #my_div twice, which is inefficient.
You can improve this either by assigning the result of a selector (i.e. var x = $('.something')) and manipulate the variable x, or you can chain your method calls like this:
$('#my_div').css('background','red').attr('name','Red Div');
You'll see the above code used a lot, because you're finding the element once. The css() method will apply a CSS style and return the actual result of $('#my_div'), so you can invoke another method, in this case attr().
My preferred way of handling the re-use of selectors is to store them as a variable, and wrap my stuff in a closure.
if you're using jQuery selector (like $('#element')), then yes, you should always store your results.
if you're using object and wrapping it in jQuery (like $(this)), it's not necessary, because jQuery doesn't need to search for that element again.
One thing that I find is generally overlooked is just how powerful jQuery chains are. It may not be so noticeable, but since jQuery caches your wrapped elements within a chain, you can modify elements, go into a more specific subset, modify, then go back up into a a general superset without much overhead.
I expect something like (pardon the example)
$('#myDiv')
.addClass('processing')
.find('#myInput')
.hide('slow')
.end()
.removeClass('processing')
;
to be better performance-wise than even
var $myDiv = $('#myDiv').addClass('processing');
var $myInput = $('#myDiv #myInput').hide('slow');
$myDiv.removeClass('processing');
This also holds for applying the jQuery function to elements returned in an event handler. Try to avoid applying $(...) too many times, because this is slow. Instead create a variable that contains the result of $(...). Good practice is to start the variable with a $, which gives a hint about the jQuery object inside the variable.
$('a').click(function(){
var $this = $(this);
$this.addClass("clicked");
$this.attr("clicked", true);
});

A few questions about JavaScript basics - $, "is not a function"

Being fully self-taught without actually reading up on JavaScript (It's my job now, believe it or not) there are a few things I accept but don't understand.
The first one is the dollar sign.
As far as I use understand it, it's a shortcut to document.getElementById(),
but if I log $ and document.getElementById() to console - Only $ returns a value. This value however is always function(), shouldn't it be. The element? What gives?
The second issue I have is something that keeps coming up in my code and I go out of my way to change the code to eliminate it. It's the "... is not a function" error.
For example:
if ($.inArray($(div_id).val(), arr) >= 0);
Will give the error .val() is not a function. Why? And how do I use the value of div_id to see if it's in array?
Hiya. When you're using Jquery (which I assume you are), then $ will return the jquery object. This can contain an array of matched HTML elements depending on the selector you used. For example $("#foo") will return the jquery object containing the element with id foo. You can get the actual HTML DOM element out using $("#foo")[0] - using the array-style notation.
Can you give us some more info on what you're trying to achieve with the $.inArray example?
$ is a valid variable name.
So if you try to use $ without setting it, it will not work.
A lot of people/frameworks however use $ as a shortcut to document.getElementById, they would declare it at the top of the script as:
function $(id) { return document.getElementById(id); }
$ and document.getElementById is not one of the same thing. $ gives you a function in console only when you are using some library like jquery which mapes $ to a function.
.val id primarly used to get value of the form elements and that is a jquery function. I think you need to learn more around javascript and jQuery
Neither Javascript nor the DOM define $, which (as other answerers said) is often defined in general-purpose DOM libraries like jQuery, Prototype or Mootools. Based on the particular code you included, I suspect you've been coding against the jQuery API (because you use $.inArray, see http://api.jquery.com/jQuery.inArray/; though your claim that $ aliases document.getElementById confuses matters, as jQuery expects CSS selectors rather than element IDs).
When $ is expected but undefined, that usually means you'll need to include the library whose API you're using in the HTML document.

Categories