PDA

View Full Version : simple javascript code does not run, no matter what browser



matthiasM
02-06-2018, 08:45 PM
Hello there,

the code below is the finalshot from this video:
https://www.youtube.com/watch?v=_Szdctv38Ow

But even the more simple code till minute 2:55 doesnt run.
Its not that an error occures, just nothing happend, no matter what browser I use.

It Holds true for all other code examples I tried.
It Holds true even if I call the html doc with its path (like: C:/User/name...) believing maybe neatbeans blocks the js code.

I use neatbeans on windows 10, and on win7 (this one is free of any antivirus software).

So, if any of you can tell me whats the reason, that would be nice.

Thanks, matthias



<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<script type ="text/javascript">
function addListeners()
{
if (window.addListeners)
{
document.getElementById('mybtn').addEventListener("click", btn1func, false);
}
else if(window.attachevent)
{

{
function btn1func(){
alter(this.id+" : mouse-click makes script run" );
}
}
}
window.onload = addListeners;
</script>

</head>
<body>
<button id="mybtn">MyButton</button>
</body>
</html>

molendijk
02-07-2018, 06:33 PM
Your code contains a number of errors. I corrected them.
I also removed the if(window.attachevent) part because we don't need that anymore.
Here's your code
<!DOCTYPE html>
<html>

<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">

<script>
function addListeners(){
document.getElementById('mybtn').addEventListener("click", btn1func, false)

function btn1func(){
alert(this.id+" : mouse-click makes script run" );
}
}

window.onload = addListeners;
</script>

</head>

<body>
<button id="mybtn">MyButton</button>
</body>

</html>

coothead
02-08-2018, 09:18 AM
Hi there matthiasM,


putting the script before the closing body tag - </body> -
is now the recommended method to use.
This will also do away with the need for "window.onload".

Here is an example...



<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<link rel="stylesheet" href="screen.css" media="screen">

<style media="screen">
body {
background-color: #f0f0f0;
font: 100% /162% verdana, arial, helvetica, sans-serif;
}
</style>

</head>
<body>

<input id="count" type="button" value="click count = 0">

<script>
( function( d ) {
'use strict';
var count = 1;
d.getElementById( 'count' ).addEventListener( 'click',
function() {
this.value = 'click count = ' + count ++ ;
}, false );
}( document ) );
</script>

</body>
</html>



coothead

matthiasM
02-08-2018, 06:31 PM
Hi coothead,
your code runs. So I changed mine like you said, set the script between body tags, but it still doesnt show any reaction.
The code by itself its old, as the creater of that video said. But is this the reason for not do anything?

molendijk
02-08-2018, 08:24 PM
Hi coothead,
My impression was that matthiasM was new to javascript and would be lost if I changed his code too much. So I only corrected the errors.

As for what you said about replacing the load event with putting scripts immediately before the closing body tag, that does not always yield good results. For instance, if we have a function img_height() containing the line alert(document.getElementById('the_img').clientHeight) for a big image that has id='the_img' and whose height is not specified, then simply putting <script>img_height()</script> at the end of the body section gives '0' or nothing at all if the image hasn't loaded yet by the time the DOM is ready. (Scripts (no onloads) put at the end of the document execute as soon as the DOM is ready, at which stage images might not have finished loading yet. So these scripts might execute too early). Here's an example of how things can go wrong:

<body>
<!-- stuff -->

<!-- scripts (no onloads) at the end end of body section -->
<script>
/*create a unique image source so that this page works with continued testing, see http://dean.edwards.name/my/busted.html*/
var src = "http://www.nasa.gov/images/content/84857main_EC04-0325-23_lg.jpg?" + Number(new Date);

/*document.write used for demonstration purposes */
document.write("<img id='the_img' src=" + src + " >");
</script>

<script>

function img_height()
{
alert(document.getElementById( 'the_img' ).clientHeight);
}
</script>

<script >
<!-- This fails if the image hasn't finished loading yet when the DOM is ready -->
img_height()
</script>
</body>
In this example, the script at the end of the body section fails. But if we replace <script>img_height()</script> with <script>window.onload=img_height</script>, it gives the correct result.

So there are cases where scripts clearly should not (try to) execute as soon as the DOM is ready, meaning that there are cases where we cannot do without some kind of onload. As we don't always know what sort of things might be still loading when the DOM is already ready (think of complicated layouts, deep DOM structures, dynamic HTML from other scripts, images), it's always safest indeed to put scripts in an onload event in cases of doubt. In this respect, attaching event listeners to onloads must be preferred to simply doing window.onload, because the former method dispenses us from writing special code in the case of multiple onloads. The load event can best be written like this:

<script>
window.addEventListener('load', function (){img_height()}, false);
</script>
This kind of onloads can be written when and wherever we want them, and we may have lots of them on our page. No worries abouts onloads being overridden by other onloads when event listeners are attached to them.

What goes for load events also applies to resize events. So we can have things like

<script>
window.addEventListener('resize', function (){img_height()}, false);
</script>

when we want, wherever we want them, and in any number.

I'd like to mention on a side note that certain lines I found in the sources of jQuery.js files make me think that this library uses a method for loading and resizing that is similar to what I explained above. Anyhow, with jQuery too, we can do multiple onloads and onresizes none of which will override the others. We could do, if we wanted:

<script>
$(window).load(function() {
some_function();
});
</script>

<script>
$(window).load(function() {
some_other_function();
});
</script>

<script>
$(window).resize(function() {
$(window).load();
});
</script>
etc. This would cause some_function() and some_other_function() to execute after page load and when the window is resized, and would be equivalent to:

<script>
window.addEventListener('load', function(){some_function()}, false);
window.addEventListener('resize', function(){some_function()}, false);
</script>

<script>
window.addEventListener('load', function(){some_other_function()}, false);
window.addEventListener('resize', function(){some_other_function()}, false);
</script>
(Of course, we would write down all of this in a more elegant way, but that's not relevant here).

coothead
02-08-2018, 10:13 PM
Hi there molendijk,


this is how I would have coded your test example...



<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<link rel="stylesheet" href="screen.css" media="screen">

<style media="screen">
body {
margin: 0;
background-color: #f0f0f0;
font: 1em/150% verdana, arial, helvetica, sans-serif;
}
#the_img {
display: block;
width: 100%;
height: auto;
}
</style>

</head>
<body>

<script>
( function( d ) {
'use strict';

var img = d.createElement( 'img' );
img.setAttribute( 'src' , 'http://www.nasa.gov/images/content/84857main_EC04-0325-23_lg.jpg?' + Number( new Date() ) );
img.setAttribute( 'id', 'the_img' );
img.setAttribute( 'alt' , 'image description' );
img.addEventListener( 'load',
function() {
alert(document.getElementById( 'the_img' ).clientHeight);
}, false );

d.body.insertBefore( img, d.getElementsByTagName( 'script' )[ 0 ] );

}( document ));
</script>

</body>
</html>



coohead

molendijk
02-09-2018, 12:04 AM
Hello coothead,
Yes, you can of course deal width the Nasa-image problem the way you do. But you could only do it because you knew what was causing the problem. The real question is whether or not we always know exactly what hasn't finished loading yet when the DOM is ready. If we don't know or if it would take a considerable effort to find it out, it seems more reasonable to me to apply the onload-method I proposed (in case of a script failure only, of course). I was hesitant myself in using onloads instead of putting scripts at the end of the document until I found out that doing multiple onloads can be done without extra (custom) scripting if event listeners are attached to them.

jscheuer1
02-09-2018, 04:52 AM
I think all you folks are likely way overthinking this. In the original posted code there are a number of typos, an outdated tag attribute (not important) and an antiquated check for a method no longer used (also not important if done correctly, which it was not). The actual intent of the code from the first post in this thread appears to be (BTW tested and works):


<!DOCTYPE html>
<html>
<head>
<title>Add Event Listener Demo</title>
<meta charset="UTF-8">
<script>
function addListeners(){
document.getElementById('mybtn').addEventListener("click", btn1func, false);
}
function btn1func(){
alert(this.id + " : mouse-click makes script run" );
}
window.addEventListener('load', addListeners, false);
</script>
</head>
<body>
<button id="mybtn">MyButton</button>
</body>
</html>

Do not copy code from a message that the forum sends you, it might be corrupted. Log on and copy the code directly from the post.

The cache may need to be cleared and/or the page refreshed to see changes.

Demo:

http://jscheuer1.com/demos/tidbits/alert.htm

For more than you probably need or want to know about this, see also:

http://www.dynamicdrive.com/forums/entry.php?255-Version-5-Events

molendijk
02-09-2018, 10:51 AM
John, that's very similar to the code I already posted in #2, except that I put function btn1func() inside function addListeners() and used a simpe window.onload instead of an event listener attached to the load (your code). In doing so, I followed the code given in the YouTube video referred to by matthiasM, and which he did not manage to copy without errors. My code in #2 is exactly the code presented by matthiasM himself (and the video) without his errors.
In the subsequent discusssion with coothead and as a reaction to his first post, I argued in favor of what you are doing yourself in your own code, namely attaching an event listener to the load instead of simpy putting window.onload. That discussion may have given the impression of overdoing things, but was simply centered around the question whether or not putting scripts at the end of the body section can do away with the need for a load event (window.onload or equivalent code). Coothead argued in favor of this statement, I argued against it.

matthiasM
02-09-2018, 03:59 PM
Hello jscheuer,
Your code its the same, but without the if parts, if I dont miss anything.
What is it what the maker of that video does not mentioned. I mean the if has its els part so it should work.

matthiasM
02-09-2018, 04:02 PM
@jscheuer, soemthing else, I'm postiv surprised for now, that a mod came around and clear some here. I cant send a pm, so keep it short.

jscheuer1
02-09-2018, 07:28 PM
The main difference about what's being done in the video is that it takes into account Internet Explorer 8 and less - those browser's inability to follow the standard event model. Virtually no one uses those browsers, so their proprietary attachEvent method no longer needs to be a part of any modern code.

jscheuer1
02-09-2018, 09:53 PM
I can go a little further. If you do want make this code backward compatible with older IE versions (all the way to IE 5), you can do this:


<!DOCTYPE html>
<html>
<head>
<title>Add Event Listener Demo</title>
<meta charset="UTF-8">
<script>
function addListeners(){
if(window.addEventListener){
document.getElementById('mybtn').addEventListener("click", btn1func, false);
} else if(window.attachEvent){
var el = document.getElementById('mybtn'),
oldbtn1func = btn1func;
btn1func = function(){oldbtn1func.apply(el);};
el.attachEvent('onclick', btn1func);
}
}
function btn1func(){
alert(this.id + " : mouse-click makes script run" );
}
if(window.addEventListener){
window.addEventListener('load', addListeners, false);
} else if(window.attachEvent){
window.attachEvent('onload', addListeners);
}
</script>
</head>
<body>
<button id="mybtn">MyButton</button>
</body>
</html>

But it's entirely unnecessary unless you need to support these older browsers, which, as I've said, virtually no one uses any longer. If you want to be useful in all sorts of environments, it can be good to know how to cater to antiquated software/machines (it's the older machines that are limited sometimes to run older software). This is only critical if your target audience is in a (internet technology speaking sense) backward country or organization.

matthiasM
02-11-2018, 08:09 PM
well, I dont know what to tell, thanks of course.
Hope thats the reason for all the other exmples from which I picked up the code and nothing happend.
Is there any way to proof that? Lets say maybe with another IDE?

jscheuer1
02-11-2018, 09:24 PM
Integrated development environment? Yes, that would do it if it included those earlier browsers. But one can use IE 11 and it's developer console's emulation feature to see what earlier IE versions would make of code. There are some limitations. But it's mostly accurate. I have the advantage of previous experience, so you can 99% trust what I just told you. To be 100% sure you would have to find a way to test in the actual browsers.

Something I would add, even for people who are limited by their machines as to what IE version they can run, those people almost always have the option of running an older version of Netscape and/or Firefox, both of which adopted the standard event model long before IE did. Because of that, and the fact that very few people are so limited, I tend to advise against trying to be so backward compatible unless you know for a fact that's necessary. That said, there are times when your target audience will be limited to both an older machine and an older version of IE. That's increasingly rare, but it still could at least theoretically happen. For general purposes though, just sticking to the standard event model* is more than adequate.

*Standard Event Model (as previously posted):

<!DOCTYPE html>
<html>
<head>
<title>Add Event Listener Demo</title>
<meta charset="UTF-8">
<script>
function addListeners(){
document.getElementById('mybtn').addEventListener("click", btn1func, false);
}
function btn1func(){
alert(this.id + " : mouse-click makes script run" );
}
window.addEventListener('load', addListeners, false);
</script>
</head>
<body>
<button id="mybtn">MyButton</button>
</body>
</html>

matthiasM
02-12-2018, 04:43 PM
I have the advantage of previous experience, so you can 99% trustI have no doubt, but I dont think you want to ask me here all the time I have tried any new youtube example.

I'm not an english native, I've read your answer many times, would straight agree that I missanderstand any of it, but cant see what it is.

matthiasM
02-15-2018, 05:03 PM
some other videos, there are more, none of the code shows any reaction.
https://www.youtube.com/watch?v=NO-U0vP5ikA
https://www.youtube.com/watch?v=AnOAZsezLEg

Have you ever heard about the krueger Effekt? Some kind of proof like, why stupid people easier belive themselfs ****ing smart