Michael Woodruff
Michael Woodruff

Reputation: 45

Modify a site's jQuery code with Greasemonkey

How do I modify or override a site's jQuery code with Greasemonkey. The jQuery library is already loaded by the site and the jQuery custom code is something I would like to change/modify. How do I override it with Greasemonkey?

For instance I would like to override this code (written by website):

  $('.side-nav-flyout').hover(function() {
        $(this).children('ul').fadeIn();
    }, function() {
        $(this).children('ul').fadeOut();
    });

With this (my override):

 $('.side-nav-flyout').hover(function() {
    $(this).children('ul').show();
}, function() {
    $(this).children('ul').hide();
});

Specifically where do you put the override code in the userscript and do I wrap it in a document.ready?

Upvotes: 1

Views: 782

Answers (3)

Ben Blank
Ben Blank

Reputation: 56572

If you're okay with completely clobbering the page's .fadeIn() and .fadeOut() methods, you can always take the "brute force" approach:

unsafeWindow.$.fn.fadeIn = unsafeWindow.$.fn.show;
unsafeWindow.$.fn.fadeOut = unsafeWindow.$.fn.hide;

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227240

What if you were to unbind the hover event, then re-bind it with yours?

$('.side-nav-flyout').unbind('hover').hover(function() {
    $(this).children('ul').show();
}, function() {
    $(this).children('ul').hide();
});

Upvotes: 1

chprpipr
chprpipr

Reputation: 2039

According to Greasemonkey's FAQs...

Greasemonkey lets you add JavaScript code (called "user scripts") to any web page, which will run when its HTML code has loaded.

This won't allow you to replace any code that is executed prior to Greasemonkey's scripts. It does allow you to overwrite anything that will be accessed or run in the future like global variables, object properties and functions. I always think of it like "Once the page has loaded, I want to change X, Y and Z". Using your example, if that code was in a function like this:

function ShowItems() {
    $("div.fadeList").each(function() {
        $(this).children('ul').fadeIn();
    });
}

you could overwrite it so that subsequent calls would run your code...

function ShowItems() {
    $("div.fadeList").each(function() {
        $(this).children('ul').show();
    });
}

If you're just looking to alter the page to your liking, you could just do something like this:

$("div.fadeList ul).show();

Upvotes: 0

Related Questions