patternjavascriptMinor
Can this code be improved? jQuery with SharePoint
Viewed 0 times
thissharepointcanimprovedwithjquerycode
Problem
I have written some JavaScript code with jQuery to create collapsible webparts in SharePoint 2010.
Can someone suggest some improvements? As I think that the methods I am using for selectors are not ideal. The solution works perfectly as it is, I just want to ensure that I am being as efficient as possible.
Below is a snippet of the HTML that I am doing the processing on.
UPDATE: Just a note, I am starting from
And this is the jQuery that I am using:
Can someone suggest some improvements? As I think that the methods I am using for selectors are not ideal. The solution works perfectly as it is, I just want to ensure that I am being as efficient as possible.
Below is a snippet of the HTML that I am doing the processing on.
UPDATE: Just a note, I am starting from
s4-wpTopTable because it is the best way for me to ensure I am dealing with a SharePoint webpart.
Links
//CONTENT WILL BE IN HERE
And this is the jQuery that I am using:
jQuery(function($) {
$('.s4-wpTopTable').find('tr:first h3').append('');
var Collapse = "/_layouts/images/collapse.gif";
var Expand = "/_layouts/images/expand.gif";
$('.min').click(function(){
var img = $(this).children();
$(this).closest('.s4-wpTopTable').find('tr:first').next().toggle().is(":visible") ? img.attr('src',Collapse) : img.attr('src',Expand );
});
});
Solution
$('.s4-wpTopTable').find('tr:first h3')...is the same as
$('.s4-wpTopTable tr:first h3')...Only one hit for jQueury goodness instead of two.
also you're attaching the click handler after putting it into the DOM. You can do it the other way:
// ...
.append(
$('')
.click(function(){
var img = $(this).children();
$(this)
.closest('.s4-wpTopTable')
.find('tr:first')
.next()
.toggle().is(":visible") ? img.attr('src',Collapse) : img.attr('src', Expand);
})
);Code Snippets
$('.s4-wpTopTable').find('tr:first h3')...$('.s4-wpTopTable tr:first h3')...// ...
.append(
$('<a class=\'min\' style=\'float:right\'><img src=\'/_layouts/images/collapse.gif\'/></a>')
.click(function(){
var img = $(this).children();
$(this)
.closest('.s4-wpTopTable')
.find('tr:first')
.next()
.toggle().is(":visible") ? img.attr('src',Collapse) : img.attr('src', Expand);
})
);Context
StackExchange Code Review Q#6920, answer score: 3
Revisions (0)
No revisions yet.