Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color and number onclick of a div

I'd like to change a color and number of a html element on click of a div. For example, when you click up-arrow the number changes from 4 to 5 and the color changes as well.

initial state

↑ 4 ↓

upvoted

5

down voted

3

here's what I have so far.
I know how to change the color of a div on click, however I don't know how to change the color of a div from an onclick of a different div. And then on top of that add the +1 or -1.

http://jsfiddle.net/64QpR/23/

note- user:uneducatedguy just asked this same question however he deleted it because people were making fun of him since he called it a fiddle in stead of a jsfiddle.

like image 988
thedullmistro Avatar asked Jan 28 '13 22:01

thedullmistro


People also ask

How can change background color of button in click?

Use HTML DOM Style backgroundColor Property to change the background color after clicking the button. This property is used to set the background-color of an element.

How do I change the color of text when clicked in CSS?

The colour of selected text can be easily changed by using the CSS | ::selection Selector. In the below code, we have used CSS ::selection on <h1> and <p> element and set its colour as yellow with green background.

Can I use onClick on div?

We can bind a JavaScript function to a div using the onclick event handler in the HTML or attaching the event handler in JavaScript. Let us refer to the following code in which we attach the event handler to a div element. The div element does not accept any click events by default.


1 Answers

Using Knockout this is really simple:

HTML:

<div class="arrow-up" data-bind="click: num.upvote.bind(num)"></div>
<h5 data-bind="text: num.value, css: { pink: num.changed }">3</h5>
<div class="arrow-down" data-bind="click: num.downvote.bind(num)"></div>

javaScript:

function Num(value) {
    this.value = ko.observable(value);
    this.changed = ko.observable(false);
}

Num.prototype.upvote = function() {
    this.value(this.value()+1);
    this.changed(true);
}

Num.prototype.downvote = function() {
    this.value(this.value()-1);
    this.changed(true);
}

var model = {
        num: new Num(1),
}

ko.applyBindings(model);

See it in action:

http://jsfiddle.net/bikeshedder/UvKsz/

With protection against multiple votes:

http://jsfiddle.net/bikeshedder/UvKsz/1/

like image 182
bikeshedder Avatar answered Sep 17 '22 23:09

bikeshedder