Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 2 of 3 FirstFirst 123 LastLast
Results 16 to 30 of 43

Thread: JS fundamentals

  1. #16
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Or yet another (perhaps more practical):-

    Code:
    <input type = "button" class = "myButton" value = "Button 1">
    <input type = "button" class = "myButton" value = "Button 2">
    <input type = "button" class = "myButton" value = "Button 3">
    
    <script type = "text/javascript">
    
    window.onload = function() {
    document.body.onclick = function(e) {
    var x = (e && e.target) || (window.event && event.srcElement);
    var v = x.value;
    if (x.className == "myButton") {
    alert ("Hi there - You  pressed " + v)
    }
    }
    }
    
    </script>

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  2. #17
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,133
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Actually, this might be the most OO version yet, more matching what he may have been expecting.

    You know, Philip, with the script AFTER the <input>s like that, you don't need to use window.onload with it's anonymous function.

    Just
    Code:
    document.body.onclick = function(e) {
      var x = (e && e.target) || (window.event && event.srcElement);
      var v = x.value;
      if (x.className == "myButton") {
        alert ("Hi there - You  pressed " + v)
      }
    }
    is plenty.

    Come to think of it, I guess it wouldn't matter where in the page you placed that. It still doesn't need the window.onload.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  3. #18
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by Old Pedant View Post
    It still doesn't need the window.onload.

    It will not work with the script in the <head>, in that case you need the window.onload. Otherwise the script must come after the <body> tag. The window.onload anonymous function may or may not be redundant depending on tne position of the script, but it does no harm.

    I agree with felgall that scripts should best be placed at the end before the </body> tag, though.
    Last edited by Philip M; 09-22-2012 at 08:35 AM. Reason: Typo

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  4. #19
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,910
    Thanks
    56
    Thanked 544 Times in 541 Posts
    just making sure there's no meat left on the bones...

    Code:
    <body>
    <input type = "button" value = "whatever">
    <input type = "button" value = "something">
    <input type = "button" value = "something else">
    <button>another thing</button>
    
    <script type = "text/javascript">
    window.onload = function() {
    document.body.onclick = function(e){
    var x = (e && e.target) || (window.event && event.srcElement);
    for (var j = 0; j < x.attributes.length; j++) {
    if(x.attributes[j].nodeValue=="button"){alert ("hi")}
    }
    if(x.tagName=="BUTTON"){alert ("hi")}
    }
    }
    </script>

  5. #20
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,910
    Thanks
    56
    Thanked 544 Times in 541 Posts
    or more simply...
    Code:
    document.body.onclick = function(e){
    var x = (e && e.target) || (window.event && event.srcElement);
    if(x.type=="button"||x.tagName=="BUTTON"){alert ("hi")}
    }

  6. #21
    New Coder
    Join Date
    Aug 2012
    Posts
    17
    Thanks
    10
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by AndrewGSW View Post
    FWIW
    It is valuable for me (as for hundreds thousand programmers over the world) because I think in OO terms, which are much more advanced than older ones.

    JavaScript is object-oriented
    According all codes in this thread it is not. More, all codes here just cry: "I am not an OO. More I am the perfect example of non-OO approach". I cannot state at this time about the language - I am a novice with it. May be this impression appears because code authors are OO-ignorant.
    FYI OO is not what marketers say about it, but the paradigm, which allows people create complicated systems, which could not be created without it, and many of those which were created would became manager's nightmare in course of inevitable changes.

    but this aspect of (pure) JS is not directly relevant to your question (manipulating DOM elements).
    Tell me please, what else but DOM manipulation should do JS for browsers. It does something beyond, but just to support its main and the only function - DOM objects manipulation.

    Sorry, I have to interrupt myself now. CU later
    Monkeys push buttons, humans push their brains
    David Biedny, Photoshop Channel Chops (my first and still the best book on Photoshop. (May be it is the best one, because authors followed their own motto)

  7. #22
    New Coder
    Join Date
    Aug 2012
    Posts
    17
    Thanks
    10
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by AndrewGSW View Post
    Sub-classing DOM elements.
    The link
    Code:
    "http://robskelly.com/2011/11/subclassing-dom-elements-in-javascript/"]Sub-classing
    requires too much time to load. So I stopped it. I still do not know, if it is accessible at all. However you can get access to the article by http-ing to
    Code:
    http://robskelly.com/2011/11/
    and then clicking on "...Continue reading" for the article. And you will see author's statement in the very beginning.
    Quote Originally Posted by the author of the link
    Subclassing DOM Elements in JavaScript
    Posted on November 2, 2011 by admin
    Ok, you actually can’t do that. But you can do something that feels the same. The trick is ...
    So the author says that is just a trick. Using tricks has unavoidable restrictions
    But this could only apply to elements that are dynamically created AFAIK .
    And finally you join the author and me, stating that JS is NOT object oriented. Well... you say JS is object-oriented, it is DOM which is not. But we are speaking about JS in browsers. The same way one could say "Fortran is object-oriented, that it is 'Integer' and 'float' which are not" May be it is true, but who cares about pure Fortran without integer and float?
    Monkeys push buttons, humans push their brains
    David Biedny, Photoshop Channel Chops (my first and still the best book on Photoshop. (May be it is the best one, because authors followed their own motto)

  8. #23
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,133
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    So long as you persist in believing that JavaScript and the DOM are one and the same, there is no hope of convincing you that JavaScript is Object Oriented.

    You prejudiced beliefs are standing in the way of your understanding the truth about JavaScript.

    For what it is worth, there is no theoretical reason that a browser couldn't make the DOM accessible to other languages. (And, in fact, MSIE does so, but that's another topic.)

    I don't know what you consider OO languages, but if you are referring to Java and C++ and C#, et al., then you are wrong. They are CLASS oriented. You can use them to write object oriented programs, true, but AS LANGUAGES they are not inherently object oriented.

    JavaScript is. ANY OBJECT in JavaScript can have members added to it! Both data and method members. AT RUN TIME. Try that with Java or C++ or C# or whatever you are claiming is an OO language. SmallTalk may be the only other real world example that I know of that is capable of what JavaScript is, and of course it is pretty nearly a dead language today. (I am of course leaving out tons of academic languages that will never see the light of day outside of university settings.)

    Try this in any of your SO CALLED object oriented languages:
    Code:
    <script type="text/javascript">
    var s = "this is just a demo";
    try {
        alert( s.properCase() );  // The String object doens't come with a properCase method
    } catch( e ) {
        alert( "properCase not supported" ); // so you will see this message
    }
    
    // but now we DYNAMICALLY add that method to the String object:
    String.prototype.properCase = 
        function() 
        {
            var words = this.toLowerCase().split(/\s/g);
            for ( var w = 0; w < words.length; ++w )
            {
                words[w] = words[w].charAt(0).toUpperCase() + words[w].substring(1);
            }
            return words.join(" ");
        };
    
    // and now when we invoke it, it works just as we wanted it to
    alert( s.properCase() );
    </script>
    Go on. Show me the equivalent in any other language of your choice.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  9. #24
    New Coder
    Join Date
    Aug 2012
    Posts
    17
    Thanks
    10
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Old Pedant View Post
    I think you mean CLASS-oriented. Whereby you add a method to the button class and of course all buttons get it.
    I do not know, what the CLASS-oriented is. I speak about Object Oriented - the totally accepted methodology. Yes, it allows AMONG OTHER THINGS to package methods in one place. But it is that, what older methodologies do as well [gosh, may I name "new" the methodology having roots in operating systems development and spacecrafts control of 60s-70s, which got its current vocabulary in 80s, loudly promoted and won general computing field in 90s? Strictly speaking "OO" is a technology of 20th century.)

    OO approach states that everything in the Universe is an object and objects are incarnations of classes.
    What I need are two of three whales of OO - encapsulation and inheritance (I planned to discuss practice of inheritance in the next thread, but learned here that JS is different kind of animal)

    Encapsulation requires that all functionality (properties, methods, and events) of an object were described in one place, and cannot be accessed any way but via this description. The "window.onload" approach violates this rule, as it spreads computations between the onload place and other places.
    The sequences of violation this rule (for more-or-less complex systems) are development and management problems during development cycle and literal nightmare during support and refactoring cycles. Just mention two of them

    1. When you develop something simple just to admire your grandmother such problem does not exist. But you may do not do anything. She is admired just by the fact of your existence. Although it will not resolve your financial problems, until she is a blindly loving billionaire. (And even if it is so, you want to establish yourself as an independent, smart and I-can-do-it kid. Don't you? )

    2. The other problem is that the part, related to "window.onload" in complex systems may write somebody else, may be in other department, may be on other continent. You may ask him/her to add one line of code. You may not to ask him/her to add complicated logic. You understand of course that the "alert('hi')" in my question is just a placeholder.

    3. I can list many other problems inevitable when this rule is violated, but as I wrote in this thread, I am not intended to write an OO manual here.


    You actually can do something like this, but it only would work if you created all the buttons as new objects, using JavaScript.
    Sounds as a reasonable requirement.But why do I need such restricted and a second-class language like JavaScript (I get this impression from this forum, learning that I can't do this, can't do that...) at all. If I do not use merits of HTML/CSS but just code in some language, I can run a local server and use such first class languages like Java, Ruby,... you name them. The power of JS is that browsers speaks it along with HTML/CSS/XML. If I will not use them, but a JS alone, why should I bother myself with such under-language?

    If I am the only one, who has noticed it now (although I do not think that I am the first - it is so obvious for a person with experience, who started the JS study), in time many people will realize that, and JS will be wiped out by more powerful and "modern" languages. The workflow is obvious: the local server gets, say XML or JASON, or YAML or ... data, converts it to the simplest HTML page and sends the page to the local browser. Voila!. Or there will be found money and willing to encapsulate that better language into browsers like it had been done with JavaScript. Does JS rainmakers understand that?

    The real problem is that when you create elements in HTML, JavaScript doesn't get to do anything to/with them until after the page is loaded and long after they are created by the browser. So you are stuck using ex post facto code to attach/add/modify the browser elements, which are *NOT* strictly speaking JavaScript objects. It is just that the browser allows JavaScript to access the elements, but they are foreign objects to JavaScript.
    Understand. Thank you, buddy. So I see it is just two cases if JS survives in next 2 generations of programers.
    1. JS rainmakers will wakeup and change something.
    2. You are wrong.
    My current experience in JS does not allow me to judge you by myself, so could you review your statements and acknowledge, or dismiss them?

    Do *NOT* confuse JavaScript-the-language with the Document Object Model (DOM) supplied by the browsers as a means for JavaScript to work with the Document Objects.
    99.99% share of cause of tremendous success JS as a language is due to its success in browsers. Have JS loses browsers it will lose everything. Besides, I think that other JS applications have the same problem. Just I did not try to use JS in other than a browser field.

    Summarizing all above, I ask

    Is JavaScript in danger of death?

    Just try to be less emotional and more rational when discussing.
    Monkeys push buttons, humans push their brains
    David Biedny, Photoshop Channel Chops (my first and still the best book on Photoshop. (May be it is the best one, because authors followed their own motto)

  10. #25
    New Coder
    Join Date
    Aug 2012
    Posts
    17
    Thanks
    10
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    I agree with felgall that scripts should best be placed at the end before the </body> tag, though.
    Why?
    The common programming practice requires put declarations in the top. There should be very strong reasons to go against common.
    What are they?
    Monkeys push buttons, humans push their brains
    David Biedny, Photoshop Channel Chops (my first and still the best book on Photoshop. (May be it is the best one, because authors followed their own motto)

  11. #26
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,133
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Is JavaScript in danger of death?
    Oh, yes. Nobody is using it. Nobody is developing with it. Google has abandoned it entirely. It will certainly die soon. By geological time. (In point of fact, there is probably more new code being written in JavaScript than any other language. Certainly there is much more web-oriented code in JS than in any other language.)

    I might note, in passing, that as of today there simply is no other language that is supported by all browsers and that is capable of such intimate interaction with the HTML DOM. I certainly am not saying that other such languages can't exist, but given JavaScript's 16-year headstart, they will take many years to be as accepted as JavaScript.

    And if you don't understand the difference between a class-oriented language and an object-oriented language, don't blame me. Again, I never said you can't use a class-oriented language for object-oriented development. (Heck, I even created an OODBMS that interacted natively with both Java and C++. And worked on another OODBMS that supported other class-oriented languages. If you don't know what an OODBMS is, look it up.)

    ***********

    Why put scripts at the bottom of the page? More reasons than there is any point in going into. If you really cared you could read the many posts in this forum about it. Or google for it. Among other things, it means that window.onload( ) is not needed.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  12. #27
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,609
    Thanks
    0
    Thanked 645 Times in 635 Posts
    Quote Originally Posted by zygezund View Post
    Why?
    The common programming practice requires put declarations in the top. There should be very strong reasons to go against common.
    What are they?
    Yes the declarations go at the top - both those declared via the JavaScript var statement AND ALL the HTML that the JavaScript code needs to reference - hence the actual JavaScript code ends up immediately before the </body> tag so that all the declarations it needs to reference go above it.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  13. The Following 2 Users Say Thank You to felgall For This Useful Post:

    Old Pedant (09-24-2012), Philip M (09-24-2012)

  14. #28
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,133
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Quote Originally Posted by felgall View Post
    Yes the declarations go at the top - both those declared via the JavaScript var statement AND ALL the HTML that the JavaScript code needs to reference - hence the actual JavaScript code ends up immediately before the </body> tag so that all the declarations it needs to reference go above it.
    VERY nice way of looking at it! Wish I'd thought of saying it that way.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  15. #29
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,133
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    OO approach states that everything in the Universe is an object and objects are incarnations of classes.
    You know, in all the noise, I missed that one.

    The first part of the statement there is half-true. Except for a bare handful of languages (and none of the major ones), certain primitive types are not objects. In general, this means numeric and boolean values. Some languages consider strings to be primitive types, too (but not JavaScript...and not Java/C++/C#). The notion of primitive types doesn't seem to upset anybody but the purists, but then the purists don't use the major languages.

    The second half of that statement is ONLY true of the CLASS ORIENTED languages. If a language doesn't have classes, it can't very well be true that an object is an instance of a class, can it? JavaScript doesn't have classes. So that second half doesn't apply to JavaScript. (JavaScript has prototypes. We might say that JavaScript is a prototype-based language except that I think that might imply some limitations that JavaScript doesn't have.)
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  16. #30
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,292
    Thanks
    10
    Thanked 583 Times in 564 Posts
    Quote Originally Posted by xelawho View Post
    actually I was talking about querySelectorAll, which is kind of CSS-ish, in the way that zygezund was asking about.
    But being that IE<9 doesn't support it, it's pretty much as useless as getElementsByClassName at this point.
    both of those work in IE8. IE7 is down to opera-levels.
    there's no reason to make everything double complicated anymore; use the good code and don't worry about a rapidly vanishing minority.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%


 
Page 2 of 3 FirstFirst 123 LastLast

Tags for this Thread

Posting Permissions

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