onload not getting called for object element [duplicate] - javascript

This question already has answers here:
Load event not fired on Safari when reloading page
(2 answers)
Closed 4 years ago.
I have an object element in my html with a blank data attribute which is then set later upon a ajax response. Now I want to get the event when the DOM for the object content document is ready.
If I use onload on the object element it works in firefox and Opera but it does not work in Webkit based browser.
How can I have the onload event trigger in all the browsers
The html looks like this
<object id="myobj" data="" />
the javascript that works in FF but not in WebKit is
e = doc.getElementById("myobj")
e.onload = function(){}
e.data="http://myurl"

In theory onload is strictly for the body element. If certain browsers allow it for other elements more power to them but it's not required.
Also: is your semicolon key broken?

I've tried the code with Safari 5.0.2 and it worked. You can verify by alerting after assigning the new value. When you view the source it isn't there but the newly assigned value can be accessed from any method.
e.data="http://myurl";
alert(e.data);
ie:
function doThis() {
var data = document.getElementById("myobj");
alert('retrieved from a method ' + data.data);
}

In jQuery, to call something on page load, all you have to do is use:
$(document).ready(function()
{
//your code here to populate your object's data attributes
});
This will work in all browsers.

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()

is 'slot' a reserve word in newer version of ECMAScript? [duplicate]

This question already has answers here:
JS function named `animate` doesn't work in Chrome, but works in IE
(3 answers)
Closed 1 year ago.
It's an issue with google chrome version 53.0.2785.101 (64-bit). I tried running a simple html file and it throws the error 'slot.testFun is not a function' when I used the word 'slot'.
<html>
<head>
<title>TEST</title>
</head>
<body>
Click Here
<script type="text/javascript">
var slot = {
testFun: function(){
console.log('clicked');
}
}
</script>
</body>
</html>
There are no conflicts with this variable in our code. It's just the browser, not allowing the variable name in this latest version.
If you use any other name except the word 'slot', it works fine.
This isn't an ECMAScript issue, it is a DOM issue.
The slot attribute has a corresponding slot property, and onclick attributes do stupid things with with so you are effectively calling this.slot.testFun() because it finds slot (which defaults to being an empty string) before it gets to the right scope.
slot is a new addition to the DOM and support for slot is new in Chrome 53. It does not appear in Chrome 52 and might not have made it even into the latest version of other browsers.
The solution: Avoid intrinsic event attributes. Bind event handlers with DOM instead. That protects you from his clash and future-proofs you from future additions to the DOM.
Click Here
<script type="text/javascript">
var slot = {
testFun: function(){
console.log('clicked');
}
}
document.querySelector("a").addEventListener("click", slot.testFun);
</script>

Javascript onclick unusual behavior [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
I'm making a calendar script and it works ok with the Opera browser, but not with firefox. The trouble happens in the day selection. This particular snippet illustrates the problem. In this case, dayofweek[] contains 31 DIV tags each containing its own number that people can click on.
<script type="text/javascript">
var maxdays=31;
for (var n=1;n<=maxdays;n++){
dayofweek[n].onclick="selectday("+n+")";
}
function selectday(day){alert(day+" is selected");}
</script>
This script works (in opera) by printing a message that the correct number is selected. In Firefox, the onclick event never is executed even tho I made clicks..
The other method I tried is this:
<script type="text/javascript">
var maxdays=31;
for (var n=1;n<=maxdays;n++){
dayofweek[n].onclick=function(){selectday(n);}
}
function selectday(day){alert(day+" is selected");}
</script>
This time, both firefox and opera respond, but the problem is that "31 is selected" appears no matter which number I select.
Does anyone know what I can do to make all javascript enabled internet browsers cooperate with my code?
Javascript is not block scoped. Try this:
<script type="text/javascript">
var maxdays=31;
for (var n=1;n<=maxdays;n++){
dayofweek[n].onclick=selectdaywrapper(n);
}
function selectdaywrapper(day) {
function selectday(){
alert(day+" is selected");
}
return selectday;
}
</script>
The issue you are running into has to do with scoping and how variables are bound in js. The functions you are creating in the loops are binding to the loop variable, but are not evaluated till after the loop finishes, so all the onclick events are executing with the final value of n

Div is not created before javascript run

I have a question about javascript/html.
First, I have this:
var post = document.body.getElementsByClassName("post");
var x=post[i].getElementsByClassName("MyDiv")[0].innerHTML;
I get from the debugger that x is not defined, it doesn't exists.
This javascript function runs onload of the body. I am sure that I gave the right classnames in my javascript, so it should find my div.
So, I read somewhere that sometimes javascript does not find an element because it is not yet there, it is not yet created in the browser ( whatever that means).
Is it possible that my function can't find the div with that classname because of this reason?
Is there a solution?
So, I read somewhere that sometimes javascript does not find an element because it is not yet there, it is not yet created in the browser ( whatever that means).
Browsers create the DOM progressively as they get the markup. When a script element is encountered, all processing of the markup stops (except where defer and async have an effect) while the script is run. If the script attempts to access an element that hasn't been created yet (probably because its markup hasn't been processed yet) then it won't be found.
This javascript function runs onload of the body.
If that means you are using something like:
<body onload="someFn()"...>
or perhaps
<script>
window.onload = function() {
someFn();
...
}
</script>
then when the function is called, all DOM nodes are available. Some, like images, may not be fully loaded, but their elements have been created.
If it means you have the script in the body and aren't using the load event, you should move the script to the bottom of the page (e.g. just before the closing body tag) and see if that fixes the issue.
Okay, instead of calling functions with
body onload, use jQuery's ready() function, or, if you don't want to use jQuery, you can use pure javascript, but this is up to you:
// jQuery
$(document).ready(function() {
var post = document.getElementsByClassName("post"),
x = post[i].getElementsByClassName("MyDiv")[0].innerHTML;
});
// JavaScript
window.onload = function initialization() {
var post = document.getElementsByClassName("post"),
x = post[i].getElementsByClassName("MyDiv")[0].innerHTML;
}
A few side notes, I don't know what the use of innerHTML
is, and also if you're doing a for loop with i then definitely
post that code, that's kind of important.
After some discussion, my answer seems to have worked for you, but you can also place your script at the end of your body tag as #RobG has suggested.

document.ready like functionality in Javascript? [duplicate]

This question already has answers here:
How to check if DOM is ready without a framework?
(7 answers)
Closed 1 year ago.
I have a requirement that states to use only plain JavaScript and not jQuery. I need to initialize some variables(using some function) as soon as the DOM is loaded and not when the page has fully loaded. In short it should not wait for the whole page to load. In jQuery it can be very easily done using document.ready() function.
Is it possible to implement it in JavaScript using any function?
a "practical" way is just placing a script block before the end of the document (even is not really equivalent to domready)
...
<script>...</script>
</body>
</html>
or use one of various pure-js implementation of DomReady event, like http://snipplr.com/view/6029/domreadyjs/
It's sometimes achieved like this
<body>
<!--
All your html tags here
....
....
-->
<script type="text/javascript">
//this should execute after the above tags and elements have rendered
</script>
</body>
You can use DOMContentLoaded event if supported:
MSDN: http://msdn.microsoft.com/en-us/library/windows/apps/hh868490.aspx
MDN: https://developer.mozilla.org/en/DOM/DOM_event_reference/DOMContentLoaded
if you realy want to wait for "ready event" you can for example use that kind of thing :
(function(w,evt,fn){
if (w.addEventListener){// W3C DOM
w.addEventListener(evt,fn,false);
}
else if (w.attachEvent) { // IE DOM
w.attachEvent("on"+evt, fn);
}
})(window,'load',function(){
// your code here
});
but it's indeed better to simply use a well placed 'script' tag as your code will probably work and start sooner

Categories