-1

How can I change the following function to trigger on document ready instead of on click? I initially removed the button and changed el.addEventListener('click', function() to document.ready(function(), but not sure what I'm missing.

//when button clicked, event listener triggered(needs to be removed so this    
//functions ONLY on page load
var el = document.getElementById('button');

var getFontFamily = function(){

    for(var i = 0; i < document.styleSheets.length; i++){
        for(var j = 0; j < document.styleSheets[i].rules.length; j++){

            if(document.styleSheets[i].rules[j].style.fontFamily){
                return document.styleSheets[i].rules[j].style.fontFamily;
            }
        }
    }

    return 'not-found';
};
//Sends event to receiving page to change font of iframed page. 
//needs to work on document.ready, not be triggered by button click on parent page
el.addEventListener('click', function(){
    var data = getFontFamily();

    window.frames[0].postMessage(data, 'http://localhost:3000');

    console.log('Message sent -->');
});

THE PAGE RECEIVING THE POST MESSAGE

window.addEventListener('message', function(e){
            document.body.style.fontFamily = e.data;

            console.log('<---Message received');
        }, false);

How can this be triggered on page ready?

Matt
  • 1,109
  • 3
  • 20
  • 49

1 Answers1

0

If you want a function to execute on load and you're not using jQuery, you can just add an event listener for the DOMContentLoaded event.

window.addEventListener('DOMContentLoaded', function(){
    var data = getFontFamily();

    window.frames[0].postMessage(data, 'http://localhost:3000');

    console.log('Message sent -->');
})
Aweary
  • 2,195
  • 11
  • 25
  • What about the page receiving the message? It is using the following: `window.addEventListener('message', function(e){ document.body.style.fontFamily = e.data; console.log(' – Matt Feb 26 '15 at 18:16