Page 1 of 2 12 LastLast
Results 1 to 10 of 17

Thread: simple javascript code does not run, no matter what browser

  1. #1
    Join Date
    Feb 2018
    Location
    germany
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question simple javascript code does not run, no matter what browser

    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


    Code:
    <!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>
    Last edited by jscheuer1; 02-07-2018 at 03:24 AM. Reason: format

  2. #2
    Join Date
    Sep 2007
    Location
    The Netherlands
    Posts
    1,782
    Thanks
    46
    Thanked 227 Times in 220 Posts
    Blog Entries
    54

    Default

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

  3. #3
    Join Date
    Nov 2006
    Location
    chertsey, a small town 25 miles south west of london, england.
    Posts
    1,145
    Thanks
    1
    Thanked 227 Times in 223 Posts

    Default

    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...

    Code:
    
    <!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
    ~ the original bald headed old fart ~

  4. #4
    Join Date
    Feb 2018
    Location
    germany
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    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?

  5. #5
    Join Date
    Sep 2007
    Location
    The Netherlands
    Posts
    1,782
    Thanks
    46
    Thanked 227 Times in 220 Posts
    Blog Entries
    54

    Default

    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:
    Code:
    <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:
    Code:
    <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
    Code:
    <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:
    Code:
    <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:
    Code:
    <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).

  6. #6
    Join Date
    Nov 2006
    Location
    chertsey, a small town 25 miles south west of london, england.
    Posts
    1,145
    Thanks
    1
    Thanked 227 Times in 223 Posts

    Default

    Hi there molendijk,

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

    Code:
    
    <!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
    ~ the original bald headed old fart ~

  7. #7
    Join Date
    Sep 2007
    Location
    The Netherlands
    Posts
    1,782
    Thanks
    46
    Thanked 227 Times in 220 Posts
    Blog Entries
    54

    Default

    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.

  8. #8
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,440
    Thanks
    78
    Thanked 3,443 Times in 3,404 Posts
    Blog Entries
    12

    Default

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

    Code:
    <!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/e...rsion-5-Events
    Last edited by jscheuer1; 02-09-2018 at 05:06 AM. Reason: add "For more than you probably . . ."
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  9. #9
    Join Date
    Sep 2007
    Location
    The Netherlands
    Posts
    1,782
    Thanks
    46
    Thanked 227 Times in 220 Posts
    Blog Entries
    54

    Default

    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.
    Last edited by molendijk; 02-09-2018 at 02:09 PM. Reason: Correction

  10. #10
    Join Date
    Feb 2018
    Location
    germany
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    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.

Similar Threads

  1. Turn simple javascript code to a button
    By JRR in forum JavaScript
    Replies: 76
    Last Post: 04-27-2015, 04:28 PM
  2. Please write a simple javascript code for me
    By laperashvili in forum JavaScript
    Replies: 2
    Last Post: 06-18-2012, 03:10 PM
  3. Replies: 1
    Last Post: 02-22-2012, 05:38 PM
  4. Replies: 3
    Last Post: 08-19-2008, 09:53 AM
  5. Looking for a simple Javascript code for a web board
    By donelian in forum Looking for such a script or service
    Replies: 1
    Last Post: 08-15-2007, 10:24 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •