Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically insert javascript using Javascript?

I am trying to dynamically insert a set of script tags with some javascript code in it using javascript. I am basically trying to wrap a file in jwplayer, but the script string is breaking rest of the javascript code in the page. How do I do this correctly?

the line causing the problem:

        $file_link_insert = "<script   type='text/javascript'>jwplayer('mediaplayer').setup({flashplayer: 'player.swf', file: '"+$href+"'});</script>";

Rest of function for ref:

$(".file_link").live("click", function(e){
                e.preventDefault();
                var $href = $(this).attr("rel");
                // Dialog           
                $('#filelink').dialog({
                    autoOpen: true,
                    width: 300,
                    modal: true,
                    buttons: {
                        "Ok": function() {
                            if($("input[name=file_link_text]").val()!=""){

                                $file_type = fileType($href);//determine if its video file see function below.

                                if($file_type == 'vid'){

                                   $file_link_insert = "<script type='text/javascript'>jwplayer('mediaplayer').setup({flashplayer: 'player.swf', file: '"+$href+"'});</script>";

                                  // $file_link_insert = " <p><a href=\""+$href+"\">"+$("input[name=file_link_text]").val()+"</a></p> ";

                                }else { $file_link_insert = " <p><a href=\""+$href+"\">"+$("input[name=file_link_text]").val()+"</a></p> "; }

                                $("#_tinyMCEinit_ifr").contents().find("body").append($file_link_insert);
                                $("#content_editor ul li:first a").click();
                                $(this).dialog("close"); 
                                $("input[name=file_link_text]").val("");
                                } else { alert("You must enter text label for your link!"); }
                            },
                        "Cancel": function() { 
                            $(this).dialog("close"); 
                            }
                        }
                }); 
            });
like image 836
user794846 Avatar asked Jan 30 '26 13:01

user794846


1 Answers

You can't include </script> within a javascript because the browser will interpret it as the end of the script. Simply break up or escape the string. like this <\/script>

See Why split the <script> tag when writing it with document.write()?

like image 126
Sam Greenhalgh Avatar answered Feb 01 '26 08:02

Sam Greenhalgh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!