0

I've made a module in JS (without jQuery) that changes the background image of a web-page based on data from the client browser (getting browser width, height and doing the appropriate stuff.. etc.) but I only know how to initialize it on page load via DOM eventListeners and I want to be able to be able to fire it via click or other user-driven events.

I don't think I'm fully grasping what I need to do to remove the EventListener without making all the rest of the code unusable, which has been the end result of my own attempts.

Any points in the right direction would be much appreciated - below is the first couple of functions called by the script:

// the initialization of the page
bindReady(function(){
    startBGResize();
});

// DOM ready handler
function bindReady(handler){
    var called = false;
    var ready = function() {
        if (called) return;
        called = true;
        handler();
    };
    if (document.addEventListener) {
        document.addEventListener('DOMContentLoaded', ready, false);
    } else if (document.attachEvent) {
        if (document.documentElement.doScroll && window == window.top) {
            var tryScroll = function(){
                if (called) return;
                if (!document.body) return;
                try {
                    document.documentElement.doScroll('left');
                    ready();
                } catch(e) {
                    setTimeout(tryScroll, 0);
                }
            };
            tryScroll();
        }
        document.attachEvent('onreadystatechange', function(){
            if (document.readyState === 'complete') {
                ready();
            }
        });
    }
    if (window.addEventListener) window.addEventListener('load', ready, false);
    else if (window.attachEvent) window.attachEvent('onload', ready);
}
StolenSheep
  • 57
  • 3
  • 13

1 Answers1

0

If you mean you want to call startBGResize when some element is clicked, you can do it like this:

var element = document.querySelector("CSS selector for the element that you'll click");
if (element.addEventListener) {
    element.addEventListener("click", startBGResize, false);
} else if (element.attachEvent) {
    element.attachEvent("onclick", startBGResize);
}

That works on all modern browsers, and also IE8.

If you're going to be hooking events regularly (and if you need to support IE8 or "compatibility" mode in later versions of IE), you might want the hookEvent function from this other answer rather than coding the if statement every time (that hookEvent also does things like patch stopPropagation and such).

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875