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
upvoted
down voted
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.
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With