Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
18
rated 0 times [  21] [ 3]  / answers: 1 / hits: 27106  / 13 Years ago, wed, april 20, 2011, 12:00:00
var index = 0;


By defualt the value of index is 0 and now i have two buttons, when i click on button 2 or 1, the value of index should get incremented. the second button on click should take the value one onwards... similarly third etc etc.


More From » html

 Answers
39

You're going to need a function to do that:



function incrementIndex() {
index += 1;
}


This assumes that your index variable is global.



Next what you'll need to do is wait for the click event. There are three ways to do that in JavaScript.




  1. Inline JavaScript



    <button onclick=incrementIndex()>Button 1</button>
    <button onclick=incrementIndex()>Button 2</button>


    This is how Hitler developed websites. Don't do this.


  2. Event Handler



    This requires you to wait until the DOM has loaded, and then get your two buttons somehow. If you only have two buttons on the page, you can do something like this (but only if this script comes after the HTML in your document):



    var buttons = document.getElementsByTagName('button');
    buttons[0].onclick = buttons[1].onclick = incrementIndex;


    Note in that example that there are no parentheses () at the end of incrementIndex.


  3. Event Listener



    The problem with event handlers is that you can only attach one function at a time. If you're going to have other JavaScript listening for button clicks, you'll have to use event listeners.



    But event listeners are a major pain in the butt because IE6-8 does it wrong, and (depending on the project) you'll probably have to code around it. At it's simplest, here's how to add an event listener in most browsers:



    var addEvent = window.addEventListener ? function (elem, type, method) {
    elem.addEventListener(type, method, false);
    } : function (elem, type, method) {
    elem.attachEvent('on' + type, method);
    };

    addEvent(buttons[0], 'click', incrementIndex);
    addEvent(buttons[1], 'click', incrementIndex);


    That is just the surface of cross-browser event listening. If you want to learn more, QuirksMode has a good series of articles on it.



[#92635] Monday, April 18, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
agustindejonm

Total Points: 738
Total Questions: 84
Total Answers: 84

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
agustindejonm questions
Fri, Jun 25, 21, 00:00, 3 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Sat, May 16, 20, 00:00, 4 Years ago
;