Okay, so here's the deal: I'm trying to create a userscript for use within Greasemonkey/Chrome/whatever else people use to manage those things. Part of what I'd like to do is to create labels for the icons I designed for this particular script. I have at least a rough idea of how to accomplish this in Jquery. The code I would have used is this:
$('li.tab.iconic').each(function (i) {
var spanName = $('this').attr(id);
var toRemove = '_button';
var spanNameCrop = spanName.replace(toRemove,'');
$('this').append('<span class="tooltip_label">'+spanNameCrop+'</span>');
});
Basically, I want to grab the id
attribute of each li
, trim the phrase "_button" from it, and insert the remaining text into the span that will be the label. My problem is that I've searched high and low but have found no clear instructions on how to do a loop like this in javascript. Is it even possible?
Alternatively, the website I'm styling does include the Jquery library. Is there a way to tell my script to load after the site has loaded jquery so that jquery script will work?
Edit: Got it working thanks to Avladov. Here's the final script.
var jQuery, $ = null;
function addJQuery(callback) {
var p = null;
if(window.opera || window.navigator.vendor.match(/Google/)) {
var div = document.createElement("div");
div.setAttribute("onclick", "return window;");
p = div.onclick();
}
else {
p = unsafeWindow;
}
jQuery = $ = p.jQuery.noConflict();
callback();
}
var myFunction = function() {
jQuery('#header .tab.iconic[id!="missinge_button"] a').css({"background-image":"url('http://i.imgur.com/2QmZG.png')"});
jQuery('#header .tab.iconic').each(function (i) {
var tabID = jQuery(this).attr('id');
var labelName = tabID.replace('_button','');
if (jQuery(this).find('span[class="tooltip_label"]').length){
}
else{
jQuery(this).append('<span class="tooltip_label">'+labelName+'</span>');
jQuery('.tooltip_label').css({'text-transform':'capitalize'});
}
});
};
addJQuery(myFunction);
If your Greasemonkey script is for a site which uses jQuery then you can use it in your script. Use this code:
var jQuery, $ = null;
function addJQuery(callback) {
var p = null;
if(window.opera || window.navigator.vendor.match(/Google/)) {
var div = document.createElement("div");
div.setAttribute("onclick", "return window;");
p = div.onclick();
}
else {
p = unsafeWindow;
}
jQuery = $ = p.jQuery.noConflict();
callback();
}
Callback is a function inside your Greasemonkey script. After doing this you can use jQuery with both jQuery and $ as if it's a normal web page JavaScript.
The benefit of this approach is that it will work not only for Firefox, but for Chrome and Opera too. It also doesn't load new jQuery script but reuses the one from the web page.
Example:
var myFunction = function() {
// Your code here
};
addJQuery(myFunction);
EDIT :
There is a way to restrict the script by using @include and @match in your script Metadata Block.
You can read more about it on GM Wiki - http://wiki.greasespot.net/Metadata_Block