Difference between 'onclick's within javascript vs. html [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 8 years ago.
<script type="text/javascript">
function translateIt() {
Microsoft.Translator.Widget.Translate("en", "es");
}
</script>
<button onclick="translateIt()">Translate</button>
<script type="text/javascript">
document.getElementById("btn").onclick = function () {
Microsoft.Translator.Widget.Translate("en", "es");
}
</script>
<button id="btn">Translate3</button>
This html block contains two buttons that should perform the exact same function. As such, the top button works but the bottom button doesn't. What is the difference between the 'onclick' implementation within html vs. within javascript?

The difference isn't with the click handler, the difference is the order of execution. In the first example you define something (the function) then reference it (in the HTML). In the second example you reference something (the HTML element) and then define it.
So in the second example the call to getElementById("btn") doesn't find anything, because at the time it executes that element doesn't exist yet.
HTML and JavaScript execute in the order in which they exist on the page as the page is being rendered. From the top of the document to the bottom.

If your second script example appears before the button, the getElementById will find no element.
By moving the script tag to after the element, it will work like normal.
<button id="btn">Translate3</button>
<script type="text/javascript">
document.getElementById("btn").onclick = function () {
Microsoft.Translator.Widget.Translate("en", "es");
}
</script>

Related

Attach dynamically loaded javascript event handler to dynamically loaded HTML [duplicate]

This question already has answers here:
Executing <script> injected by innerHTML after AJAX call
(12 answers)
Closed 5 years ago.
I have a site which loads content through AJAX. I need to attach onclick handler to some div which was dynamically loaded. It works fine if my event handler is already defined in my main javascript file (whether I attach it through markup via attribute onclick="myFunc" on by more pedantic addEventListener ).
However, I would like this event handler to be defined in a <script> tag of the dynamically loaded content. Then it doesn't work, whether <script>function myHandler(){}</script> is before or after the <div onclick='myHandler();'>.
I tried to attach it at the end of the XmlHttpRequest:
contentDiv.innerHTML = xhr.responseText;
var handlerName = getItFrom(xhr.responseText);
var clickFn = window[handlerName];
loadedDiv.addEventListener('click', clickFn);
Doesn't work neither: handlerName is correct, but clickFn remains undefined...
I prefer a pure js answer but jquery is ok if I can easily translate it.
It's doable if you're willing to use jQuery, here I assign an event handler from a script tag of a html string. A couple of things, the parameter you pass into .html has to be a jQuery object of your string, and you'll need to replace </script> with <\/script> within the string (could use .replace).
$('#content').html($("<span>before</span><script>$('#testo').click(function () { alert('infunc');});<\/script><span>after</span>"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='content'></div>
<button id='testo'>Click</button>
If getItFrom(xhr.responseText); returns a function defined in the global scope try to add quotes like this:
var clickFn = window['handlerName'];
Because console says:
var luck = function(){}; window[luck];
> undefined
var luck = function(){}; window['luck'];
> function luck()

JS onpage/window load [duplicate]

This question already has answers here:
How to run a function when the page is loaded?
(11 answers)
Closed 6 years ago.
I want to run this script on pageload or after all the elements are loaded.
JavaScript
<script type="text/javascript">
function backgroundload (){
$(".portfolio-background-color")
var color = /#[0-9\A-F]+/.exec($(this).html())[0];
$(this).css('background', color)
}
window.onload = backgroundload;
</script>
i'm new to js please check if my code is okay and is it the correct way to load the js
All Javascript runs on page load. If what you mean is that you want it to run after all the elements in the page have been initialized, there are several ways:
window.onload
document.onload
body.onload
$(document).ready
There are more in-depth explanations of the support for the first three, and the differences between them, here. Documentation for $(document).ready is here.
However, in my experience, the easiest way to ensure that a script runs after all synchronously-loaded content is simply to place the <script> element at the bottom of the <body>.

Function doesn't execute from an onclick inside the html [duplicate]

This question already has answers here:
JavaScript not running on jsfiddle.net
(4 answers)
Closed 8 years ago.
this is probably stupidly easy but I'm very new to JavaScript and it's driving me nuts.
My question, why doesn't this work:
http://jsfiddle.net/Ye9tG/
<input type="button" id="butt" value="Button" onclick="getThought();"/>
It works fine if I add the onclick directly into the JavaScript:
document.getElementById("butt").onclick = getThought;
Thanks in advance.
Your getThoughts function isn't defined, because your JavaScript is set to execute onLoad. See the dropdown menu in the upper left of jsFiddle. Select "No wrap - in <head>" to resolve the issue: http://jsfiddle.net/Ye9tG/1/
Also, always take a look at your browser's console to check for errors. In this case, you'll see a Uncaught ReferenceError: getThought is not defined error when clicking the button.
In the top left corner of jsfiddle you'll see that your fiddle is set to run your js code "onLoad". What that really means is that jsfiddle creates this for you:
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
// YOUR CODE HERE
}//]]>
</script>
As a result, your function is only accessible within that onload function. Change the value to "no wrap head" and you'll see that it works.
Your other option would be to make your function explicitly global:
window.getThought = function(){
// ...
http://jsfiddle.net/Ye9tG/5/

Does "innerHTML" depend on eventhandlers? [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 9 years ago.
first one:
function change(){
document.getElementById("clr").style.backgroundColor="red";
document.getElementById("test1").innerHTML="hwllo world";
}
second one:
document.getElementById("test1").innerHTML="hwllo world";
The first one is working fine. But the second one is not working when the file is loaded.
Javascript and HTML rendering are executed in the sequence they are found in the file. So if you're executing a piece of JS before an HTML element is rendered then the JS code wouldn't work.
This will fail:
<script>
document.getElementById("test1").innerHTML="hwllo world";
</script>
<div id="test1"></div>
This will work as expected:
<div id="test1"></div>
<script>
document.getElementById("test1").innerHTML="hwllo world";
</script>
Alternatively you can use the various onload and dom ready events to make sure that your script executes after all the HTML have been rendered:
<script>
window.onload = function(){
document.getElementById("test1").innerHTML="hwllo world";
}
</script>
<div id="test1"></div>
And what error is in console? May be you are trying to set innerHTML of not existing node? If you want to manipulate with divs, you have to do it after the page is loaded, so typically call this as body event onLoad:
<script>
function init() {
document.getElementById("test1").innerHTML="hello world";
}
</script>
<body onload="init();">
<div id="test1"></div>
...
As James Allardice said in his comment, the code is probably executed before the DOM is ready. Your code could then fail as the element might not be there. This is a known problem, but there is also a known solution. The most used solution is probably to use jQuery, which has an easy way to allow a function to only be executed after the document is ready. To use this method, first you need to include jQuery as a script reference and then modify your code as follows:
$(document).ready(function() {
document.getElementById("clr").style.backgroundColor="red";
document.getElementById("test1").innerHTML="hwllo world";
});
Now if you are using jQuery anyways, you can also rewrite your code to use jQuery selectors and make it a bit more compact:
$(document).ready(function() {
$("#clr").css("backgroundColor", "red");
$("#test1").html("hwllo world");
});
Both pieces of code are functionally equivalent.

Setting a jQuery selector as parameter for a javascript-function [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to use a variable in place of ID in jquery
I have the function called makeinvisible and one of the parameters is supposed to be a jQuery id selector for an image with id=testimage. JavaScript does not recognize it as such, hence the image does not become hidden.
function makeinvisible (imageid){
$("#imageid").css("visibility","hidden")
}
$(document).ready(
makeinvisible("testimage")
)
Any help appreciated!
The code as written is looking for an element with id=imageid.
Try:
function makeinvisible (imageid){
$("#" + imageid).css("visibility","hidden")
}
$(document).ready(
makeinvisible("testimage")
)
Edit: Your document.ready call is also incorrect. The way you have it written makeinvisible is being executed immediately, not on document ready. It needs to be:
$(document).ready(function(){ makeinvisible("testimage"); });

Categories