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 1 of 3 123 LastLast
Results 1 to 15 of 43

Thread: JS fundamentals

  1. #1
    New Coder
    Join Date
    Aug 2012
    Posts
    17
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Question JS fundamentals

    I want to alert when ANY button is clicked. I DO NOT want to add
    onclick="alert('Hi');"
    to every button description in my HTML5 code, but to do it like I would do for style. E.g.
    <style>
    something-like-this:
    button {onclick="alert('Hi');"}
    </style>


    Actually, I expect the very common object-oriented approach, which is used by virtually any language of last 2-3 decades, so I believe that it is somehow possible, but what exact code will do this particular highly simplified example?

    Please help.

    TIA
    Last edited by zygezund; 09-21-2012 at 09:48 PM. Reason: minor mistype

  • #2
    Regular Coder
    Join Date
    Apr 2012
    Location
    St. Louis, MO
    Posts
    985
    Thanks
    7
    Thanked 101 Times in 101 Posts
    getElementsByTagName('a'); will create an array of every anchor tag in the DOM.

    Well.. alright.. to be technical, it's not an array, but it's an object that can be accessed like an array.
    ^_^

    If anyone knows of a website that can offer ColdFusion help that isn't controlled by neurotic, pedantic jerks* (stackoverflow.com), please PM me with a link.
    *
    The neurotic, pedantic jerks are not the owners; just the people who are in control of the "popularity contest".

  • Users who have thanked WolfShade for this post:

    zygezund (09-22-2012)

  • #3
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,775
    Thanks
    55
    Thanked 519 Times in 516 Posts
    unfortunately in html, a button is not a button. At least not when it comes to tag names. Have a look at the different tags:

    Code:
    <input type="submit"/>
     <input type="reset"/>
     <input type="button" value="hello"/>
     <button>hello</button>
    so it depends on how your html is coded. You could search for button tags, but you would miss the others. You could search for input tags and narrow your search by type but then you will miss the button tags.

    you could give all your buttons a class name and collect them that way.

    whichever way, you can't do it css style like in your example (well, you can, but the cross-browser dramas make it not really worthwhile).

  • Users who have thanked xelawho for this post:

    zygezund (09-22-2012)

  • #4
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    Assuming we are talking about button tags (rather than inputs) the following is one approach, although it may be more detailed than the OP requires. Soz if so.

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Buttons Delegation</title>
    </head>
    
    <body>
    <h1>Event Delegation with Buttons</h1>
    
    <button id="hello">Hello</button>
    <button id="two">Two</button>
    <button id="three">Three</button>
    <button id="goodbye">Goodbye</button>
    
    <script type="text/javascript">
    var addEvent = function (elem, eventType, func) {
        if ( elem.addEventListener )
            addEvent = function (elem, eventType, func) {
                elem.addEventListener(eventType, func, false);
            };
        else if ( elem.attachEvent )
            addEvent = function (elem, eventType, func) {
                elem.attachEvent('on' + eventType, func);
            };
        addEvent(elem, eventType, func);
    };
    
    var delegateEvent = function (elem, childElems, eventType, func, args) {
        addEvent(elem, eventType, function (e) {
            var evt = e || window.event;
            var elem = evt.target || evt.srcElement;
            if ( elem.nodeName.toLowerCase() == childElems.toLowerCase() ) {
                func(elem, args);
            }
        });
    };
    
    function alertText(obj, args) {
        switch (obj.id) {
            case 'hello':
                alert('Hello there!');
                break;
            case 'two':
                alert('Hi from button 2');
                break;
            case 'three':
                alert('Howdy, button 3');
                break;
            case 'goodbye':
                alert('Goodbye you!');
                break;
            default:
                // do nothing
                break;
        }
    }
    
    function init() {
        delegateEvent(document, 'button', 'click', alertText);
    }
    
    addEvent(window, 'load', init);
    </script>
    </body>
    </html>
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #5
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    My sample code can be adapted to distinguish between buttons and input-buttons, etc.:
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Buttons Delegation</title>
    </head>
    
    <body>
    <h1>Event Delegation with Buttons</h1>
    
    <button id="hello">Hello</button>
    <button id="two">Two</button>
    <button id="three">Three</button>
    <button id="goodbye">Goodbye</button>
    <input type="checkbox">
    <input type="button" value="anything">
    
    <script type="text/javascript">
    var addEvent = function (elem, eventType, func) {
        if ( elem.addEventListener )
            addEvent = function (elem, eventType, func) {
                elem.addEventListener(eventType, func, false);
            };
        else if ( elem.attachEvent )
            addEvent = function (elem, eventType, func) {
                elem.attachEvent('on' + eventType, func);
            };
        addEvent(elem, eventType, func);
    };
    
    var delegateEvent = function (elem, childElems, eventType, func, args) {
        addEvent(elem, eventType, function (e) {
            var evt = e || window.event;
            var elem = evt.target || evt.srcElement;
            if ( elem.nodeName.toLowerCase() == childElems.toLowerCase() ) {
                func(elem, args);
            }
        });
    };
    
    function alertText(obj, args) {
        if (args && obj.type == "button") {
            alert('An input button was clicked!');
        } else if (!args) {
            switch (obj.id) {
                case 'hello':
                    alert('Hello there!');
                    break;
                case 'two':
                    alert('Hi from button 2');
                    break;
                case 'three':
                    alert('Howdy, button 3');
                    break;
                case 'goodbye':
                    alert('Goodbye you!');
                    break;
                default:
                    // do nothing
                    break;
            }
        }
    }
    
    function init() {
        delegateEvent(document, 'button', 'click', alertText);
        delegateEvent(document, 'input', 'click', alertText, true);
    }
    
    addEvent(window, 'load', init);
    </script>
    </body>
    </html>
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • Users who have thanked AndrewGSW for this post:

    zygezund (09-22-2012)

  • #6
    New Coder
    Join Date
    Aug 2012
    Posts
    17
    Thanks
    10
    Thanked 0 Times in 0 Posts
    Thank you, guys
    So I see JS seems not to be an object-oriented language. Just one hope still remains
    Quote Originally Posted by xelawho View Post
    whichever way, you can't do it css style like in your example (well, you can, but the cross-browser dramas make it not really worthwhile).
    As I do not care too much about browser wars, it might be the solution for me. Please tell us what browser do you mean, and how it could help
    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
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    FWIW JavaScript is object-oriented but this aspect of (pure) JS is not directly relevant to your question (manipulating DOM elements).

    [Well... someone might dispute this and provide an OO-solution to your question - I would be interested to see this myself.]

    Added:
    Sub-classing DOM elements. But this could only apply to elements that are dynamically created AFAIK .
    Last edited by AndrewGSW; 09-22-2012 at 01:13 AM.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #8
    Regular Coder
    Join Date
    Mar 2006
    Posts
    725
    Thanks
    35
    Thanked 132 Times in 123 Posts
    Code:
    window.onload=function(){
    
      document.body.onclick=function(e){
        var who= (e && e.target) || (window.event && event.srcElement);
        if(who.tagName=='BUTTON')alert('Hi');
      }
    }
    Last edited by mrhoo; 09-22-2012 at 01:41 AM.

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Nice, Hoo. Or even:
    Code:
    window.onload=function(){
    
      document.body.onclick=function(e){
        var who= (e && e.target) || (window.event && event.srcElement);
        if(who.tagName=='BUTTON' || (who.tagName=='INPUT' && who.type=='button')alert('Hi');
      }
    }
    Maybe should be who.type=='BUTTON'. I never remember which and didn't bother to check.
    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.

  • Users who have thanked Old Pedant for this post:

    mrhoo (09-22-2012)

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Quote Originally Posted by zygezund View Post
    Thank you, guys
    So I see JS seems not to be an object-oriented language. Just one hope still remains

    As I do not care too much about browser wars, it might be the solution for me. Please tell us what browser do you mean, and how it could help
    MSIE earlier than version 9 doesn't support getElementsByClassName.

    All other browsers, including MSIE 9, do. So:
    Code:
    var myButtons = document.getElementsByClassName("myButton");
    for ( var m = 0; m < myButtons.length; ++m )
    {
        m.onclick = function() { ...do whatever you want here... };
    }
    ********

    Actually, I expect the very common object-oriented approach, which is used by virtually any language of last 2-3 decades,...
    Ummm...I think you mean CLASS-oriented. Whereby you add a method to the button class and of course all buttons get it.

    You actually can do something like this, but it only would work if you created all the buttons as new objects, using JavaScript.

    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.

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

  • Users who have thanked Old Pedant for this post:

    zygezund (09-24-2012)

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    By the by, if you use the jQuery package, you WOULD be able to do something as simple as
    Code:
       $(".myButton").click( function() { ...do whatever you want... } );
    And that will work even in older MSIE because jQuery recognizes the lack of getElementsByClassName and supplies its own equivalent code, behind the scenes.

    jQuery uses CSS-style notation as a "selector" to find all instances of a class (when you use ".classname") or the instance of an ID (when you use "#idname"). And it allows chaining them. And. The $( ) is actually ordinary legal JavaScript: $ is a legal variable/function name in JS that jQuery co-opts as a kind of universal selector function. Then it parses the argument to that function to figure out what to do.
    Last edited by Old Pedant; 09-22-2012 at 02:06 AM.
    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
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,775
    Thanks
    55
    Thanked 519 Times in 516 Posts
    actually I was talking about querySelectorAll, which is kind of CSS-ish, in the way that zygezund was asking about.

    Code:
    <body>
    <input type="button" value="anything">
    <input type="button" value="anything">
    <input type="button" value="anything">
    <button> something </button>
    <script type="text/javascript">
    var b=document.body
    var buttons = b.querySelectorAll('input[type="button"],button')
    
    for ( var m = 0; m < buttons.length; ++m )
    {
        buttons[m].onclick = function() { alert("I'm a buttoooooon") };
    }
    </script>
    </body>
    But being that IE<9 doesn't support it, it's pretty much as useless as getElementsByClassName at this point. Nice that you can grab the input type="button and the <button>s, though...

  • #13
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Oh, doh on me. Didn't think about that.

    But, really, I think the important thing for zygezund to learn here is the difference between JavaScript-the-language and the DOM. And maybe to realize that there are frameworks/libraries (such as jQuery) that can *help* in integrating the two, if you don't mind the "expense" of dragging in the library.

    And, of course, if you did NOT use HTML to create the page and created it all with JavaScript code, you could indeed incorporate the kind of methods into your own object representations of the DOM objects that he seems to be looking for.
    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.

  • #14
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,734
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    Another way:-

    Code:
    <input type = "button" value = "Button 1">
    <input type = "button" value = "Button 2">
    <input type = "button" value = "Button 3">
    
    <script type = "text/javascript">
    
    window.onload = function() {
    document.body.onclick = function(e){
    var x = (e && e.target) || (window.event && event.srcElement);
    if (x.value.substring(0,6) == "Button") {alert ('HI')}
    }
    }
    
    </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.

  • #15
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Cute! Probably not practical, but really cute. Just shows there are so many ways to deprive the poor feline of its dermal layer.
    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.


  •  
    Page 1 of 3 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
    •