Reputation: 3
Good Evening, I am pretty new to jQuery, and therefore would like you to forgive me if I am asking a stupid question, but apparently I've been facing the following problem, which I think I cannot solve by myself.
I am trying to implement jQuery code to change the order of columns a table has. The code is as follows:
$(document).ready(function (table, from, to) {
var rows = jQuery('tr', table);
var cols;
rows.each(function () {
cols = jQuery(this).children('th, td');
cols.eq(from).detach().insertBefore(cols.eq(to));
});
}(jQuery('#changeorder'), 1, 0));
It works perfectly Having a table with the id "changeorder" in jsFiddle, but doesn't work on Drupal website. I also tried removing the $(document).ready part, and adding (jQuery); at the end, the same result.
I tried adding the code to the html.tpl.php, just after the inclusion of jQuery javascript:
<!-- jQuery library (served from Google) -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function (table, from, to) {
var rows = jQuery('tr', table);
var cols;
rows.each(function () {
cols = jQuery(this).children('th, td');
cols.eq(from).detach().insertBefore(cols.eq(to));
});}(jQuery('#changeorder'), 1, 0));
</script>
And I have also tried adding the content directly to the page where I need it with the drupal_add_js(). Still no progress.
Any idea on what I'm doing wrong?
Thanks beforehand.
Upvotes: 0
Views: 234
Reputation: 156
You should be wrapping your entire JS in (function ($) {})(jQuery); Then using your $ in place of your jQuery instances...drupal has always liked this better for me.
I would also suggest converting this into a function that you can call when needed instead of passing your variable straight to the document ready like you currently are.
(function ($) {
$(document).ready(function() {
function tableChange(table, from, to){
var rows = $('tr', table);
var cols;
rows.each(function () {
cols = $(this).children('th, td');
cols.eq(from).detach().insertBefore(cols.eq(to));
};
tableChange('#changeorder', 1, 0)
});
})(jQuery);
In my experience best practice for drupal should not be adding your scripts to your html.tpl but instead you should be adding to yourtheme.info file:
scripts[] = yourjsfiles/script.js
Then in the script.js file you can have something like the following:
(function ($, Drupal, window, document, undefined) {
$(document).ready(function(){
//your code here
});
})(jQuery, Drupal, this, this.document);
You want to try and avoid cluttering up you .tpl files. You will thank me for this in the long run :)
edit: I just noticed in your question the inclusion of jquery. This cannot be done in the manner you are attempting to do it. By default Drupal 7 uses jquery 1.4.4 and the way to update this would be the jQuery Update Module
Upvotes: 3