javascript in innerhtml not working - javascript

For example:
<html>
<div id="media">123</div>
Click
<script type="text/javascript">
function fun() {
document.getElementById("media").innerHTML = '<script type="text/javascript">alert("working");<\/script>';
}
</script>
</html>
After you click the alert does not show.
alert("working"); is just an example. I want it to finish one job other javascript
. I have a job to be processed through ajax should have used innerHTML

The HTML spec specifies that script tags inserted using innerHTML should not be executed. This is a security consideration.
There are still ways to do this if you are determined, such as adding it to img handlers or creating a script element, inserting it into the DOM and changing its text property. I will not elaborate on these, since doing this is generally considered somewhat sketchy. If you are not trying to inject script, you should include the script element in the page source.

<script type="text/javascript">
function fun() {
alert("working");
}
</script>
<div id="media">123</div> Click

Your JS function should be like this.
function fun() {
alert("working");
}

Related

Alternative to hide/show content with JS?

is there a better way to replace this kind of js function by simply collapse/toggle a div and show/hide its content?
$(function() {
$('#destselect').change(function(){
$('.dest').hide();
$('#' + $(this).val()).show();
});
});
The reason this is happening is because your js file is called on the head of your page.
Because of this, when you document.getElementsByClassName('collapsible');, colls result in an empty array, as your elements in body are not yet created.
You could either create a separate js file and add it at the end of your body (in that way you make sure your colls are created when your javascript is executed), or just wrap your code on a DOMContentLoaded event listener that will trigger your code once the document has completely loaded.
My guess would be that you are loading your script before browser finishes loading dom conetent and so when it runs the elements it is trying to add event listeners to, don't yet exist.
Try wrapping all you javascript in that file in this:
document.addEventListener("DOMContentLoaded", function(event) {
// all your code goes here
});
The above makes sure that your script is run after loading all elements on the page.
You could add a script tag to the header of your HTML file, this will import the JS file into your current page as follows
<script src="File1.js" type="text/javascript"></script>
Then call the function either in onclick in a button or in another script (usually at the bottom) of your page. Something like this:
<body>
...
<script type="text/javascript">
functionFromFile1()
</script>
</body>
Seems like your script is not executing properly due to a missing variable.
In this script https://www.argentina-fly.com/js/scripts.js
Naves variable in function UpdateDetailsDestination() is not defined.
I think you should resolve this first and then check your further code is working on not.
Please take a look into Console when running page. You'll see all JavaScript related errors there.

What must be declare or input inside the $(document).ready?

I am new to javascript so I make this thread. I read some post. In this post is the function inside or outside of the document ready. If it is declare outside the document can I re-use / call it in another JScript?.
As my title what should be the contain inside of a document ready?.
$(document).ready is an event which fires up when document is ready.
Suppose you have placed your jQuery code in head section and trying to access a dom element (an anchor, an img etc), you will not be able to access it because html is interpreted from top to bottom and your html elements are not present when your jQuery code runs.
To overcome this problem, we place every jQuery/javascript code (which uses DOM) inside $(document).ready function which gets called when all the dom elements can be accessed.
If you place your jQuery code at the bottom (after all dom elements, just before ) , there is no need for $(document).ready
See the example, which alert calls first that will give you an idea what should be inside the ready.
alert("Without Ready");
$(document).ready(function(){
alert("With Ready");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
.ready makes sure your DOM is ready and good to go for binding, so putting all your functions inside there like the events functions would only be bootstrap at ready state of the document. Normal functions( with name i.e non anonymous functions) can be declared outside the document.ready so you can re-use it somewhere else. since those functions are called from the document.ready events or jquery code to be used.
See more about document.ready here. check the snippet below for a brief example layouting
/**
Global function here, which is not called or bind on page load
*/
function alertWindow(message){
alert ("Window is loaded here with Message: "+message);
$("#console").text(message);
}
$(document).ready(function(){
$("#showBtn").click(function(event){
var ourMessage = $("#message").val();
alertWindow(ourMessage);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="message" placeholder="Enter Message" >
<br>
<button id="showBtn">Show Message</button>
<p>
<h3>Console Here</h3>
<div id="console"></div>
</p>
when we use document.ready all the listeners and all the functions inside the document ready will work only after the page load completed.
So for example if you added any listener to a button and that perform some change in your page then better to write it inside the document.ready.
First things first - In JavaScript a function defines the scope of the code it contains, so if you want to share it you need to define it in a location that your other code can see.
You also don't need to define functions inside the document ready function, you could just define outside of the ready() callback. Eg,
$(document).ready(function(){
$('button').click(function(){
somefunc();
});
});
function somefunc()
{
alert('yes');
}
$(document).ready(function(){
// do something else
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this help..
The ready event occurs when the DOM (document object model) has been loaded.
Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above.
source : http://www.w3schools.com/jquery/event_ready.asp
For example: if DOM is not fully loaded and our JS code is trying to access unloaded DOM. We will get Javascript error. To avoid this we need to give some time for loading document. To achieve this, We have a callback function for DOM loaded $(document).ready() or $(function)
We can have functions out side ready and those we can access for other JS also. It is always better to write Jquery add event and other Jquery related code inside ready method.
Refers from here:
A page can't be manipulated safely until the document is "ready."
jQuery detects this state of readiness for you. Code included inside
$(document).ready() will only run once the page Document Object
Model (DOM) is ready for JavaScript code to execute. Code included
inside $(window ).load(function() { ... }) will run once the entire
page (images or iframes), not just the DOM, is ready.
Since usually we've used jQuery to selecting and/or manipulating the DOM, so the best way to that is after the DOM is fully loaded. For those reason, so we need an event to watch the DOM ready state. This method give us flexibility where we'll write our javascript code, either on <head> nor at the end of <body>.
See my snippet samples below:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// this will not work properly
$('div').html('Hello World!!!');
</script>
</head>
<body>
<div>Hi brother!!</div>
</body>
</html>
Above script will not work properly since the script was executed
before the DOM loaded properly. So, the jquery can not find the
element with div tag.
To make the script running smooth, we need to add additional event listener from jquery named $(document).ready() as you can see at snippet below.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// this will work properly
$(document).ready(function() {
$('div').html('Hello World!!!');
});
</script>
</head>
<body>
<div>Hi brother!!!</div>
</body>
</html>
But, how if we don't want to add ready method? We still can do that, if we write the script below required DOM, see below snippet for example:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div></div>
<script>
// this will not work properly
$('div').html('Hello World!!!');
</script>
</body>
</html>
UPDATE :
Refers from OP comment below:
In your reference I read use the shorthand $() for $( document
).ready() so I can use like $() for document.ready?
YES, you can use that shorthand, see my snippet below:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// this will work properly
$(function() {
$('div').html('Hello World!!!');
});
</script>
</head>
<body>
<div>Hi brother!!!</div>
</body>
</html>

executing javascript function from HTML without event

I wish to call a javascript function from an HTML page and I do not want it dependent on any event. The function is in a separate .js file since I wish to use it from many web pages. I am also passing variables to it. I've tried this:
HTML:
<script type="text/javascript" src="fp_footer2.js">
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
</script>
The function in fp_footer2.js:
function footerFunction(path, file) {
document.write("<a href=" + path + "/" + file + " target='_blank'>Link to the original web page for this assignment.</a>");
return;
}
(I have also tried putting the fp_footer2.js file reference in the header, to no avail. I'm not sure if I can put it 'inline' like I did in this example. If not, please let me know.
PS: I know I can do this with a simple 'a href=""' in the HTML itself. I wanted to see if this could work, for my own curiosity.
If a <script> has a src, then the external script replaces the inline script.
You need to use two script elements.
The strings you pass to the function also need to be actual strings and not undefined variables (or properties of undefined variables). String literals must be quoted.
<script src="fp_footer2.js"></script>
<script>
footerFunction("1_basic_web_page_with_links", "1bwpwl.html");
</script>
JavaScript will run while your page is being rendered. A common mistake is to execute a script that tries to access an element further down the page. This fails because the element isn't there when the script runs.
So includes in the <head> will run before any DOM content is available.
If your scripts are dependent on the existence of DOM elements (like a footer!) try to put the script includes after the DOM element. A better solution is to use the document ready event ($(document).ready() in jQuery). Or window.onload.
The difference between documen ready and window onload is that document ready will fire when the DOM has been rendered; so all initial DOM elements will be available. Where as window onload fires after all resources have loaded, like images. window onload is useful if you're doing things with those images. Usually document ready is the right one.
Maybe I misunderstand your question, but you should be able to do something like this:
<script type="text/javascript" src="fp_footer2.js"></script>
<script type="text/javascript">
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
</script>
Have you tried calling it from a document.ready?
<script type="text/javascript">
$(document).ready(function() {
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
});
</script>

Execute JavaScript code at the end when the HTML has been loaded

I want to execute a function at the end when the HTML has been loaded. I tried it with onload without success. I also tried it with ready, but it still doesn’t work. Here is my code. This is again placed in the header:
<script type="text/javascript">
$(document).ready(function() {
$('#infowindow_content').html('test');
});
</script>
The div is also set by an external JavaScript file. Content:
window.onload = initialize;
function initialize() {
document.getElementById('infowindow_content').innerHTML = 'testa';
}
It is included the following way before the closing body tag:
<script type="text/javascript" src="../lib/functions.js"></script>
I tried to place the above code before the closing body tag, but currently I have no idea why this doesn't work (the content isn't changed by my JavaScript code). If I execute it on the console afterwards everything works fine.
Solution:
I set a configuration parameter (language) in the HTML file. In the JavaScript file I ask for this value and depending on the value I define another content. Sometimes it could be so simple ...
Try this:
setTimeout(function() {
$(document).ready(function() {
$('#infowindow_content').html('test');
});
}, 20);
I don't know the jQuery equivalent but try the native JS.
Since the <body> has the most HTML & loads after <head>...
document.body.onload=function(){
yourFunction(args)
}
<body onload="yourFunction(args)">...</body>
Or maybe the window object, since it's the root of every webpage DOM...
window.onload=function(){
yourFunction(args)
}
Always place DOM manipulating code directly before your </body> tag. JavaScript in the header should only be called to libraries, such as jQuery.

Javascript on loaded page not executed

// Change the value of the outputText field
function setAjaxOutput(){
if(httpObject.readyState == 4){
document.getElementById('maincontent').innerHTML = httpObject.responseText;
}
}
i try to load a page which contain this script
<script type="text/javascript">
$(document).ready(function() {
alert('dfd');
$("#formAddUser").validate({
rules: {
userImage: {
required: true,
accept: "png|jpg|gif|jpeg"
}
}
});
});
</script>
<div class="content-box">
<div class="content-box-header">
........................
Why javascript on loaded page not executed? Thank you.
Your problem is that innerHTML doesn't execute scripts in the HTML fragment. When you say 'element.innerHTML = htmlfragment;', it just adds the tags and renders the HTML. Script tags are not rendered as part of the HTML by the browser, so they are ignored.
You need to use jQuery.load() instead of jQuery.ajax() like this:
$('#maincontent').load('yourscript.php');
jQuery.load(); has code inside that first takes those tags out, then adds the remaining HTML via innerHTML, then runs the tags separately. You can see the code that does this here at around line 211. From the docs:
When calling .load() using a URL without a suffixed selector
expression, the content is passed to .html() prior to scripts being
removed. This executes the script blocks before they are discarded. If
.load() is called with a selector expression appended to the URL,
however, the scripts are stripped out prior to the DOM being updated,
and thus are not executed.
first try:
<script type="text/javascript">
alert('dfd');
</script>
and then try
<script type="text/javascript">
$(document).ready(function() {
alert('dfd');
});
</script>
and paste the results.
I believe your form comes with ajax. so it is better if you can turn your validation into a function, and call it inside ajax loaded content.

Categories

Resources