Markup showing jQuery1281617118201 on Internet Explorer - javascript

I'm seeing some of the following in my markup on Internet Explorer:
<span jquery128161711820124="24"></span>
and
<span jQuery1281617118201="26"></span>
What is it?

It is a property added so that jQuery can track data associated with that element.
Things like event handlers you attach using jQuery:
$('someElement').click(function() {
// run code
});
or data you add to the element using .data()
$('someElement').data('myData', 'myValue');
are some of the associations.
jQuery doesn't add that property until it is necessary.
You can view the data associated with an element using the number at the end, as in:
jQuery1281617118201=“26”
console.log(​jQuery.cache[26]);​ // will show the data for element number 26 in the cache

I'm not 100% sure, but I think it's a property set by jQuery to speed up DOM element selection.
I would think the reason that it only appears in IE is that it laks support for a bunch of native getElements methods (ie. document.getElementByClassName)
EDIT:
I was partly right (I think). In the source code of (jQuery 1.4.2) at line 986 it's a generated attribute base on the now() method. The underlying method seems to have with cache of jQuery to do. The cache is used when selecting elements so you don't have to fetch the same element twice.

Was that code generated by your app or it's found in a third party code?
It looks like an internal jQuery variable used to maintain a state or to point to another jQuery (DOM) object.

Related

.eq() out of order

I'm trying to select the 3rd element of a JQuery object, by using eq() method. But for some reason the 2nd and 3rd selections pop out in changed order:
var selection = $("[name=input0], [name=input1], [name=input2], [name=input3]");
selection.eq(1); //turns out to be input2!!
What could be the reasons for this behavior? Can I trust acessing it by index in my script?
According to:
https://api.jquery.com/multiple-selector/
The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.
With the help of the answers and comments and a bit of reading on the documentation.
Turns out that jQuery selects elements in the order they appear in the DOM (HTML), so:
Using a direct array access to a jQuery selection will work if you use that order, but you can only trust it if you are also responsible for the HTML, and you would need to remember this if you are ever going to change the layout.
Bottom line: not the best way to select a specific element.

Modify dynamically added elements on load using jQuery

I am converting old jQuery version 1.2.6 code that we use with our portal (Liferay). Previously we used the livequery plugin to add events to dynamically added DOM objects. This is now a feature built-in to jQuery (the on() function). I have that figured out.
However, there was also a feature in livequery that allowed us to modify these dynamically loaded objects on load (i.e. not tied to certain events):
$(".myTextBox").livequery(function() { $(this).val("initial value"); });
I do not control the code when the ajax portlets get loaded in our portal, so I can't modify the content when created.
I've tried a few things to no avail. Here is the one that I thought would work, but doesn't. I added jQuery to my portlet so that it loads at the bottom of the portlet HTML and I added jQuery to the file.
<footer-portlet-javascript>myscript.js</footer-portlet-javascript>
...
$(document).ready(function() {
$(".myTextBox").val("initial value");
});
This doesn't work. If I write an alert($(".myTextBox")) it shows an object, but alert($(".myTextBox").val()) is undefined.
Any ideas of how I can get working?
From what I read, you want to wire up events to items that have not been necessarily added to the DOM yet at the time you're wire-up function fires. I also read that you are upgrading to a more recent version of jquery.
If you're using jquery 1.7+, the .on() method should provide this capability for you. If you're using something between 1.2.6 and 1.7, you'll need to use the .live() method to achieve this behavior.
$(".myTextBox").live('click', function(e){
console.log(this.value);
});
Optionally, you may want to mix in some AUI to do your wiring-up on the Liferay 'allPortletsReady' published event. Here is some code we've used to wire-up items once all portlets are finished loading:
//This is the AUI version of on document ready
// and is just used to form a 'sandbox'(clojure)
// around our code so the AUI object A is not modified
AUI().ready(function(A){
//This essentially subscribes the provided function
// to the Liferay custom event 'allPortletsReady'
// so that when it's fired, the provided function
// will be called.
Liferay.on('allPortletsReady', function(){
//Do your initialization here
myCustomPortletManager.init();
//OR
A.one("#mySelector").on('click', function(e){
//do your work here
});
//Etc.
//NOTE: jQuery ($) is valid inside this sandbox for our
//instance.
});
}):
Well you can setInterval to iterate checking new element.
setInterval(function(){
var $ele = $('.myTextBox:not(.loaded)'); // find new element that not loaded
if($ele.size() > 0){
$ele.each(function(){
// do stuff with elements
$(this).val("initial value");
}).addClass('loaded'); // flag this element is loaded
}
}, 200); // set delay as you wish
by the way, I'm not recommended this.
First, you probably want to use an ID instead of a class in this case to ensure you are referring specifically to a single element.
Where your alert is will determine whether this code is executed before or after. This would explain that you return an object, but no value. Put it after the value assignment, either on the page or temporally.
The following works just fine (http://jsfiddle.net/4WHyE/1/):
<input id="myid"/>
$('#myid').val('some value')
alert($('#myid').val())
If you must use class, then it depends on whether you want to set each class element individually or all to the same value. If you wish them all to have the same value, simply replace id with class in the above example:
<input class="myclass"/>
$('.myclass').val('myvalue')
If you wish to set unique values, you can simply iterate through them (http://jsfiddle.net/4WHyE/2/):
$('.myclass').each(function(index){
$(this).val('value' + index)
});

When jQuery .attr('onclick') function return a event object?

I am just debugging jQuery in FireBug and wonderig about the return value of
$('.a-selector').attr('onclick');
It turns out to be an onclick(event), but I have read some code before and the author just uses it like this:
$('.a-selector').attr('onclick').replace(..., ...);
which means it can be treated as a String Object. But it reports an error when I use like this.
My jQuery version is 1.5.2. So I wonder when the jQuery changes the API and what is the best way to change the onclick event defined in the HTML.
When jQuery .attr('onclick') function return a event object?
In jQuery < 1.6. That's because prior to 1.6, .attr() did a mix between retrieving properties and attributes where it saw fit, newer versions removed that layer of witchery and now have proper methods for retrieving attributes (.attr) and properties (.prop).
Here's a fiddle demonstrating the above.
ps. BTW, it doesn't return an event object, but rather a function object that serves as event handler. =]
Also, 2 side notes: You should always upgrade your jquery to the latest version when viable (currently 1.8.3), it comes with more features, better performance and lots of bug fixes.
And you shouldn't really be using onclicks when you have jQuery, that goes against the Web 2.0 standards of separation of structure (html) and behavior (js) - jQuery itself provides cross-browser handler attaching with the methods .on() (for jQuery 1.7+), and .bind/.delegate/.live for older versions.
I assume that you want to change the value of your onclick attribute of some element.
$('.a-selector').attr('onclick',''); // leave 2nd parameter blank if you want to remove its value
OR
$('.a-selector').attr('onclick','myfunc()');
############################### Edit
You can define your function as below :
<script>
function myfunc(){
// Do stuff here
}
</script>
is it a possibility for you to reset the click event?
$('.a-selector').unbind('click').click(function() {
// new function
});
to replace text in an javascript-code is normally not that what javascript should do. I think there is a much better solution possible.

jQuery .length() speed implications

Whenever I want to find if an element exist in the DOM I use the following code.
if($('#target').length){
// do stuff.
}
This works well and I use it quite a lot on client sites.
Question:
How fast is this method? What are the speed implications when this is used a lot in a project?
You would be much better off using if(document.getElementById('target')) instead. JavaScript is always faster than jQuery (since jQuery is just a bunch of JavaScript hidden under the carpet)
EDIT: If you use it a lot, you can make a custom function:
function idExists(id) {return !!document.getElementById(id);}
Native JS is always faster than a query through jQuery. It just may not be as friendly.
After running a query through jsperf.com, native (querySelectorAll) is 57% faster than jQuery
However, if you use id, jQuery will be faster than querySelectorAll. In any case of id, use document.getElementById to test for an elements existence.
http://jsperf.com/jquery-obj-length
Try searching a DOM element with JQuery context say:
if an element u search say, an Input control, lies with in a table, pass table as your context:
A simple example:
$(function(){
var name= $('#Name','#mytab').val();
alert(name);
});
the jquery engine find the element 'Name' with in 'mytab' and not the entire form
follow this fiddle link : http://jsfiddle.net/NzbJr/10/

What is the difference between removeProp and removeAttr in JQuery 1.6?

If you removeProp on something you should have used removeAttr() on will it silently fail? Will it work? Will it actually remove the entire attribute or just the value inside it?
If checked is added using removeProp(), can it be removed with removeAttr()?
Many questions!
The official jQuery blog provides a very clear explanation:
In the 1.6 release we’ve split apart
the handling of DOM attributes and DOM
properties into separate methods. The
new .prop() method sets or gets
properties on DOM elements, and
.removeProp() removes properties. In
the past, jQuery has not drawn a clear
line between properties and
attributes. Generally, DOM attributes
represent the state of DOM information
as retrieved from the document, such
as the value attribute in the markup
. DOM
properties represent the dynamic state
of the document; for example if the
user clicks in the input element above
and types def the .prop("value") is
abcdef but the .attr("value") remains
abc.
In most cases, the browser treats the
attribute value as the starting value
for the property, but Boolean
attributes such as checked or disabled
have unusual semantics.
For example, consider the markup
<input type="checkbox" checked>. The
presence of the checked attribute
means that the DOM .checked property
is true, even though the attribute
does not have a value. In the code
above, the checked attribute value is
an empty string (or undefined if no
attribute was specified) but the
checked property value is true.
Before jQuery 1.6, .attr("checked")
returned the Boolean property value
(true) but as of jQuery 1.6 it returns
the actual value of the attribute (an
empty string), which doesn’t change
when the user clicks the checkbox to
change its state.
There are several alternatives for
checking the currently-checked state
of a checkbox. The best and most
performant is to use the DOM property
directly, as in this.checked inside an
event handler when this references the
element that was clicked. In code that
uses jQuery 1.6 or newer, the new
method $(this).prop("checked")
retrieves the same value as
this.checked and is relatively fast.
Finally, the expression
$(this).is(":checked") works for all
versions of jQuery.
An attribute of an element is something like 'class'. Whereas its property would be 'className'.
This is the reason for adding jQuery.prop and jQuery.propHooks into version 1.6, to make it easier working with both.
So if the the property had the same name as the attribute you could use both removeProp or removeAttr.
I asked a similar question on jQuery forum, got this answer:
Yes, attr is meant for html attributes
as they are strictly defined. prop is
for properties. So for instance, say
you have a node elem with class
"something" (raw element not jQuery
object). elem.className is the
property, but is where the
attribute resides. Changing the class
attribute also changes the property
automatically and vise versa.
Currently, attr is jumbled and
confusing because it has tried to the
job of both functions and there are
many bugs because of that. The
introduction of jQuery.fn.prop will
solve several blockers, separate code
as it should have been separated from
the beginning, and give developers
faster functions to do what they
expect them to do. Let me make up a
percentage for a sec and say that from
my experience in the support IRC and
reading other's code, 95% of the use
cases for attr will not have to switch
to prop.
EDIT
It may be best to stick to using either jQuery.attr or jQuery.prop. Theres seems to be some strange behaviour when setting and removing the checked attribute using both.
See here for an example: http://jsfiddle.net/tomgrohl/uTCJF/
There is a bug in 1.6 to do with selected: http://bugs.jquery.com/ticket/9079
Using jQuery 1.6, I was was trying to clone a menu item which had several id attributes, and so I did this:
$('ul.menu').clone().filter('*').removeProp('id').appendTo('.sidebar');
When I inspected the elements in Firebug I had a lot of id="undefined" - not what I wanted. So now I am using removeAttr and it seems to work much better.
$('ul.menu').clone().filter('*').removeAttr('id').appendTo('.sidebar');

Categories

Resources