If you have used Stack Overflow for a while, you surely have used the function of vote up and down of the question and answer. I notice Stack Overflow uses <a> anchor. But I don’t know how to POST the data to server. I think it’s JavaScript associated with this <a>, but I can’t find it. How can I implement it?
If you have used Stack Overflow for a while, you surely have used the
Share
Yes, JavaScript is involved. There are two parts: Hooking up a handler for the click events on the voting “buttons”, and sending data to the server.
Hooking up the events is well-covered elsewhere and I won’t go into it here. (For instance, I cover it in this answer.)
Sending the data to the server, you can use ajax. On any browser that isn’t completely obsolete, you can use
XMLHttpRequest:On more up-to-date browsers you can use
fetch:Just for fun, here’s a complete example:
HTML:
JavaScript:
Some notes:
hrefon the links (which StackOverflow doesn’t have), so that if JavaScript is disabled, we can fall back to going to a page where we let the user vote using a form submission or something. Also, links withhrefare treated specially by browsers (tab targets, etc.), so this is useful for accessibility. (To really do that, I’d probably have to put the article ID in thehrefas well.)data-attribute.closestfunction starts with the element and examines that element to see if it fits the given CSS selector, then if not looks at its parent, then its parent, etc., until it finds a match. So the vote buttons are associated with the article by containment; the article being voted on contains the voting buttons.closestcheck with acontainscheck to ensure that the element the handler is attached to contains the element that was found (in case it was found in an ancestor element instead). That would be!voteLink || !this.contains(voteLink)above (instead of just!voteLink).