3

I´m modifying the appearance of two drop down lists. No problems here. Everything works great. The only issue is that the addEventListener method only works at page refresh.

How do I make this code work at page load without hitting the refresh button?

window.addEventListener('load', function () 
{
    var CityCount = this.character.citynum ;
    var PosX = parseInt(CityCount) * (-15);
    var MyHeight = parseInt(CityCount) * 15 - 15;
    var MyStyle='div#citylist {width: 150px !important; margin-top: ' + PosX + 'px !important; position: absolute !important; height: ' + MyHeight + 'px !important; overflow: auto !important; padding-left: 1px !important}';
    addGlobalStyle(MyStyle);
    addGlobalStyle('div#my_city_list {width: 150px !important; margin-top: 50px !important;}');
}, false)
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Dani
  • 39
  • 1
  • 5

1 Answers1

1

You didn't list the target page, but it probably uses AJAX to set and/or change that global variable.

In addition, the question-code will break if the script loses its @grant none status, or if you try to use it on any browser but Firefox. (Unless the script uses Injection -- which we can't tell from the question.)

To get around the AJAX problem, poll for the variable inside a setInterval().
To make the code more robust, use unsafeWindow or Script Injection. See "Accessing Variables from Greasemonkey..." for more information.

Putting it all together, this should work. addEventListener() is not needed:

var globScope       = unsafeWindow || window;
var cityCountTimer  = setInterval (styleTheCityList, 333);

function styleTheCityList () {
    this.lastCityCount  = this.lastCityCount || 0; // Static var for this func

    if (
            typeof globScope.character          != "undefined"
        &&  typeof globScope.character.citynum  != "undefined"
    ) {
        var CityCount  = parseInt (globScope.character.citynum, 10);
        if (CityCount !=  this.lastCityCount) {
            var PosX        = CityCount * (-15);
            var MyHeight    = CityCount * 15 - 15;
            var MyStyle     = 'div#citylist {width: 150px !important; margin-top: '
                            + PosX
                            + 'px !important; position: absolute !important; height: '
                            + MyHeight
                            + 'px !important; overflow: auto !important; padding-left: 1px !important}'
                            ;
            addGlobalStyle  (MyStyle);
            addGlobalStyle  ('div#my_city_list {width: 150px !important; margin-top: 50px !important;}');

            this.lastCityCount = CityCount;
        }
    }
}
Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • Many thanks! Your code works great. I only need to run the code once so i removed this.clastCityCount lines and i´ve added _clearInterval(cityCountTimer)_. – Dani Dec 08 '12 at 04:35