user1331315
user1331315

Reputation: 1

Enable disable buttons html5/css/javascript

i have made a calculator. i have uploaded it on the following webpage.

www.vipulshree.com

i want to highlight a button on clicking it and remove highlight from it when another button is clicked. when the next button is clicked, it should change color/disable/highlight and the previous button comes back to normal. Please help me ive searched all over the net for this and could not find anything. Help me im desperate.

Thank You.

Upvotes: 0

Views: 2450

Answers (3)

Madara's Ghost
Madara's Ghost

Reputation: 174957

Use the :focus CSS pseudo-selector. It will match the element currently having focus. Seems to not work on buttons


Use JavaScript to add a class .focused on click, and remove it on all other elements. Use event delegation on the common parent of all buttons (in this code, it's assumed to be #container).

<script type="text/javascript">
    setFocus = function(e) {
        if (document.getElementsByClassName('focus')[0]) document.getElementsByClassName('focus')[0].className = '';
        if (e.target.tagName.toLowerCase() == 'button') {
            e.target.className = 'focus';
        }
    };
    document
       .getElementById('container')
        .onclick = setFocus;
</script>

My HTML markup looked like this:

<div id="container">
    <button>1</button>
    <button>2</button>
    <button>3</button>
    <button>4</button>
    <button>5</button>
</div>

Working Example

Upvotes: 1

GillesC
GillesC

Reputation: 10874

here is a little jsfiddle working example, it's using jQuery only for the dom ready loader and a CSS class to do the highlight effect.

http://jsfiddle.net/t6bJ3/

    var buttons = document.getElementsByTagName('button'),
        buttonsLength = buttons.length,
        selected, 
        i = 0, 
        reset = function() {
            for (i = 0; i < buttonsLength; i++) buttons[i].className = '';
        },
        highlight = function(ev) {
            reset();
            ev.target.className = 'highlight';
        };

    for (; i < buttonsLength; i++) buttons[i].onclick = highlight; 

Upvotes: 0

me_digvijay
me_digvijay

Reputation: 5492

You can define a class for your buttons and then using the click event you can change its color, and when you click on any button save it in variable say "previous".

So when you click any other button you again change the color of the saved button variable and assign the current button to that variable.

var previous;
document.getElementsByClassName("className").onclick = function (){
    // change the color of the previous element
    previous = this;
    // change the color of this button
}

Upvotes: 1

Related Questions