a little js cleanup

This commit is contained in:
Mark Moser
2017-03-06 16:31:00 -06:00
parent 858c9b2eeb
commit 2cc94ba296
5 changed files with 2 additions and 43 deletions

View File

@ -0,0 +1,27 @@
function handleAjaxResponse($el, callback) {
var $header = $('header');
$el.on("ajax:success", function(e, data){
$header.after('<div class="success">' + data.message + '</div>');
callback(data);
}).on("ajax:error", function(e, xhr) {
if (xhr.status === 400){
$header.after('<div class="error">' + xhr.responseJSON.join('<br>') + '</div>');
} else {
$header.after('<div class="error">Oops! There was an error processing your request. Please try again.</div>');
}
});
}
function updateVotes(data){
$("[data-id=up-votes]").html(data.upCount);
$("[data-id=down-votes]").html(data.downCount);
$("[data-id=my-vote]").html(data.myVote);
}
$(document).ready(function() {
$('[data-id=ajax-action]').each(function(){ handleAjaxResponse($(this)); });
});
$(document).ready(function() {
$('[data-id=vote-count]').each(function(){ handleAjaxResponse($(this), updateVotes); });
});

View File

@ -0,0 +1,25 @@
$.fn.extend({
characterLimiter: function(limit, label) {
this.on("keyup focus show", function() {
setCount(this, label);
});
// TODO: append label container after $this, instead of hard HTML
function setCount(src, label) {
if(src !== undefined) {
var chars = src.value.length;
if (chars >= limit) {
src.value = src.value.substr(0, limit);
chars = limit;
}
label.html(limit - chars);
}
}
setCount(this[0], label);
}
});
$(document).ready(function() {
$('textarea').characterLimiter(1000, $(".chars span"));
});