简体   繁体   中英

How can I add javascript to the head of an html document to listen for a click on an element not yet added to the DOM?

I am using a third party web app that allows you to place your own code in the head of the HTML page. The rest of the document is auto-generated so the only place I can insert custom code is in the head before everything is added to the DOM.

I am trying to add click events to the various buttons that will be loaded in the DOM. I want the browser window to resize depending on the id of the button clicked.

I tried something like this:

    <script type="text/javascript">
window.onLoad=function(){
    document.getElementById("resize").onClick = window.resizeTo(250, 250);
    };
</script>

because I was hoping that if I used the onLoad event to add an onClick event it would wait until everything is loaded and I wouldn't get a null reference error. I don't get a null reference error, but the onClick doesn't work.

I tried to use jQuery also because one post I read suggested listening for all click events and then checking the id of the element that triggered the event, however I am not sure if I am using it correctly. This is the first time I've ever used jQuery. This didn't work either.

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $(document).click(function() {
        if(event.target.id == 'resize') {
            window.resizeTo(250,250);
        };
    };
</script>

The real answer may just be that it isn't possible, but I am hoping there is some solution that I just haven't been able to find online.

To summarize, is there a way to resize the browser window based on the id of the element clicked inside of a third party web app? The script has to be in the head of the document before the elements are added to the DOM.

Thank you for your help.

You can put your code in document.ready and delegate it to the element which may be added in the future. See http://api.jquery.com/on/ for more details.

 $(document).on("click", "selector of element added in future", function(){

 //execute your code
 });

With jQuery you can have a delegated event

$(document).on("click", "<selector>", function(){}));

which works for dynamically created objects as well.

as opposed to

$("<selector>").on("click", fucntion(){});

which will only work for original DOM elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM