In my project I'm using jqPagination plugin. I really like the functionality, but I was wondering if it's possible to customize it in the way that max-page number always appears outside of the input box. Here is my link to the jsfiddle https://jsfiddle.net/webIra7/hqz90Lwj/1/
<div class="some-container">
<div class="loaded-page">First page </div>
<div class="loaded-page">Second page</div>
<div class="loaded-page">Third page</div>
</div>
<div class="gigantic pagination">
‹
<input class="pagenumber" type="text" readonly="readonly" />
›
</div>
You can access to plugin properties like this:
($('.pagination').jqPagination('option', 'max_page'))
Check the fiddle to see it working: https://jsfiddle.net/ivan0013/hqz90Lwj/5/
According to the customization section of the documentation for the jqPagination plugin, you can pass a page_string to the options. The default value is 'Page {current_page} of {max_page}'.
You could change the page_string in the options to be just 'Page {current_page}', then put the max page number in a separate HTML element outside of the pagination element.
See updated fiddle here.
You can calculate the maxPageNumber outside the jqPagination object and set this value to a span element after the next button.
To change the page format string you can use:
page_string: 'Page {current_page}',
Do not copy or include the src code of plugin, you may include it with:
<script src="https://rawgit.com/beneverard/jqPagination/master/js/jquery.jqpagination.min.js"></script>
The snippet:
$(document).ready(function () {
// hide all but the first of our paragraphs
$('.some-container div.loaded-page:not(:first)').hide();
// compute the maxPageNumber
var maxPageNumber = $('.some-container div.loaded-page').length;
// set this value as you wish:
$('#maxPageNumber').text(maxPageNumber);
// initialize the jqPagination
$('.pagination').jqPagination({
max_page: maxPageNumber,
page_string: 'Page {current_page}', // change the string format
paged: function (page) {
// a new 'page' has been requested
// hide all paragraphs
$('.some-container div.loaded-page').hide();
// but show the one we want
$($('.some-container div.loaded-page')[page - 1]).show();
}
});
});
.pagenumber::-ms-clear {
width: 0;
height: 0;
}
.pagination {
display: inline-block;
border-radius: 3px;
}
.pagination a {
display: block;
float: left;
width: 20px;
height: 20px;
outline: none;
border-right: 1px solid #CDCDCD;
border-left: 1px solid #CDCDCD;
color: #555555;
vertical-align: middle;
text-align: center;
text-decoration: none;
font-size: 15px;
font-family: Helvetica, Arial, sans-serif;
/* ATTN: need a better font stack */
background-color: #f3f3f3;
}
.pagination a:hover, .pagination a:focus, .pagination a:active {
background-color: #006699;
color: white;
border: 1px solid #cdcdcd;
}
.pagination a.previous:hover, .pagination a.previous:focus, .pagination a.previous:active, .pagination a.next:hover,
.pagination a.next:focus, .pagination a.next:active, .pagination a.disabled, .pagination a.disabled:hover,
.pagination a.disabled:focus, .pagination a.disabled:active {
background-color: #006699;
color: #A8A8A8;
cursor: default;
color: white;
}
.pagination a:first-child {
border: none;
border-radius: 2px 0 0 2px;
}
.pagination a:last-child {
border: none;
border-radius: 0 2px 2px 0;
}
.pagination input {
float: left;
margin: 0;
padding: 0;
width: 115px;
height: 20px;
outline: none;
border: none;
vertical-align: middle;
text-align: center;
}
/* gigantic class for demo purposes */
.gigantic.pagination {
margin: 0;
}
.gigantic.pagination a {
font-size: 30px;
background-color: #eee;
border-radius: 0;
color: #006699;
float: left;
height: 35px;
width: 35px;
line-height: 30px;
border: solid 1px #ccc;
}
.gigantic.pagination input {
width: 120px;
font-size: 15px;
font-family: Helvetica, Arial, sans-serif;
margin: 0;
padding: 7px 0;
}
/* log element for demo purposes */
.log {
display: none;
background-color: #EDEDED;
height: 300px;
width: 524px;
overflow: auto;
margin-left: 0;
list-style: none;
padding: 10px;
}
.log li {
margin-top: 0;
margin-bottom: 5px;
}
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://rawgit.com/beneverard/jqPagination/master/js/jquery.jqpagination.min.js"></script>
<div class="some-container">
<div class="loaded-page">First page </div>
<div class="loaded-page">Second page</div>
<div class="loaded-page">Third page</div>
</div>
<div class="gigantic pagination">
‹
<input class="pagenumber" type="text" readonly="readonly" />
›
<span id="maxPageNumber" style='margin-top: 1.00em;margin-left:1.25em; display:inline-block;'/>
</div>
HTML:
<div class="some-container">
<div class="loaded-page">First page </div>
<div class="loaded-page">Second page</div>
<div class="loaded-page">Third page</div>
</div>
<div class="gigantic pagination">
‹
<input class="pagenumber" type="text" readonly="readonly" />
›
<input class="maxPageNumber" type="text" readonly="readonly" id="maxPag" />
</div>
JS:
(function(e) {
"use strict";
e.jqPagination = function(t, n) {
var r = this;
r.$el = e(t);
r.el = t;
r.$input = r.$el.find(".pagenumber");
r.$el.data("jqPagination", r);
r.init = function() {
r.options = e.extend({}, e.jqPagination.defaultOptions, n);
r.options.max_page === null && (r.$input.data("max-page") !== undefined ? r.options.max_page = r.$input.data("max-page") : r.options.max_page = 1);
r.$input.data("current-page") !== undefined && r.isNumber(r.$input.data("current-page")) && (r.options.current_page = r.$input.data("current-page"));
r.$input.removeAttr("readonly");
r.updateInput(!0);
r.$input.on("focus.jqPagination mouseup.jqPagination", function(t) {
if (t.type === "focus") {
var n = parseInt(r.options.current_page, 10);
e(this).val(n).select()
}
if (t.type === "mouseup") return !1
});
r.$input.on("blur.jqPagination keydown.jqPagination", function(t) {
var n = e(this),
i = parseInt(r.options.current_page, 10);
if (t.keyCode === 27) {
n.val(i);
n.blur()
}
t.keyCode === 13 && n.blur();
t.type === "blur" && r.setPage(n.val())
});
r.$el.on("click.jqPagination", "a", function(t) {
var n = e(this);
if (n.hasClass("disabled")) return !1;
if (!t.metaKey && !t.ctrlKey) {
t.preventDefault();
r.setPage(n.data("action"))
}
})
};
r.setPage = function(e, t) {
if (e === undefined) return r.options.current_page;
var n = parseInt(r.options.current_page, 10),
i = parseInt(r.options.max_page, 10);
if (isNaN(parseInt(e, 10))) switch (e) {
case "first":
e = 1;
break;
case "prev":
case "previous":
e = n - 1;
break;
case "next":
e = n + 1;
break;
case "last":
e = i
}
e = parseInt(e, 10);
if (isNaN(e) || e < 1 || e > i) {
r.setInputValue(n);
return !1
}
r.options.current_page = e;
r.$input.data("current-page", e);
r.updateInput(t)
};
r.setMaxPage = function(e, t) {
if (e === undefined) return r.options.max_page;
if (!r.isNumber(e)) {
console.error("jqPagination: max_page is not a number");
return !1
}
if (e < r.options.current_page) {
console.error("jqPagination: max_page lower than current_page");
return !1
}
r.options.max_page = e;
r.$input.data("max-page", e);
r.updateInput(t)
};
r.updateInput = function(e) {
var t = parseInt(r.options.current_page, 10);
r.setInputValue(t);
r.setLinks(t);
e !== !0 && r.options.paged(t)
};
r.setInputValue = function(e) {
var t = r.options.page_string,
n = r.options.max_page;
t = t.replace("{current_page}", e).replace("{max_page}", n);
r.$input.val(t);
$("#maxPag").val("of " + n);
};
r.isNumber = function(e) {
return !isNaN(parseFloat(e)) && isFinite(e)
};
r.setLinks = function(e) {
var t = r.options.link_string,
n = parseInt(r.options.current_page, 10),
i = parseInt(r.options.max_page, 10);
if (t !== "") {
var s = n - 1;
s < 1 && (s = 1);
var o = n + 1;
o > i && (o = i);
r.$el.find("a.first").attr("href", t.replace("{page_number}", "1"));
r.$el.find("a.prev, a.previous").attr("href", t.replace("{page_number}", s));
r.$el.find("a.next").attr("href", t.replace("{page_number}", o));
r.$el.find("a.last").attr("href", t.replace("{page_number}", i))
}
r.$el.find("a").removeClass("disabled");
n === i && r.$el.find(".next, .last").addClass("disabled");
n === 1 && r.$el.find(".previous, .first").addClass("disabled")
};
r.callMethod = function(t, n, i) {
switch (t.toLowerCase()) {
case "option":
if (i === undefined && typeof n != "object") return r.options[n];
var s = {
trigger: !0
},
o = !1;
e.isPlainObject(n) && !i ? e.extend(s, n) : s[n] = i;
var u = s.trigger === !1;
s.current_page !== undefined && (o = r.setPage(s.current_page, u));
s.max_page !== undefined && (o = r.setMaxPage(s.max_page, u));
o === !1 && console.error("jqPagination: cannot get / set option " + n);
return o;
case "destroy":
r.$el.off(".jqPagination").find("*").off(".jqPagination");
break;
default:
console.error('jqPagination: method "' + t + '" does not exist');
return !1
}
};
r.init()
};
e.jqPagination.defaultOptions = {
current_page: 1,
link_string: "",
max_page: null,
page_string: "Page {current_page}",
page_string2: "of {max_page}",
paged: function() {}
};
e.fn.jqPagination = function() {
var t = this,
n = e(t),
r = Array.prototype.slice.call(arguments),
i = !1;
if (typeof r[0] == "string") {
r[2] === undefined ? i = n.first().data("jqPagination").callMethod(r[0], r[1]) : n.each(function() {
i = e(this).data("jqPagination").callMethod(r[0], r[1], r[2]);
});
return i
}
t.each(function() {
new e.jqPagination(this, r[0])
})
}
})(jQuery);
if (!console) {
var console = {},
func = function() {
return !1
};
console.log = func;
console.info = func;
console.warn = func;
console.error = func
};
$(document).ready(function() {
// hide all but the first of our paragraphs
$('.some-container div.loaded-page:not(:first)').hide();
$('.pagination').jqPagination({
max_page : $('.some-container div.loaded-page').length,
paged : function(page) {
// a new 'page' has been requested
// hide all paragraphs
$('.some-container div.loaded-page').hide();
// but show the one we want
$($('.some-container div.loaded-page')[page - 1]).show();
}
});
$('.pagination2').jqPagination({
max_page : $('.some-container div.loaded-page').length,
paged : function(page) {
// a new 'page' has been requested
// hide all paragraphs
$('.some-container div.loaded-page').hide();
// but show the one we want
$($('.some-container div.loaded-page')[page - 1]).show();
}
});
});
CSS:
.pagenumber::-ms-clear{
width: 0;
height: 0;
}
.pagination{
display: inline-block;
border-radius: 3px;
}
I include <input class="maxPageNumber" type="text" readonly="readonly" id="maxPag" /> change page_string: "Page {current_page} of {max_page}" to page_string: "Page {current_page}", page_string2: "of {max_page}" and include $("#maxPag").val("of" + n);
Related
Hey I am try to create a RGB Color game, here I am facing a Issue that when I refers the tab then inside my randomDiv() function there is a If block(color_fix) which is sometime working and sometime won't working you can check through clicking on refresh tab button inside console, please solve this problem
let first_div = document.getElementById('first_div');
let h4 = document.querySelector('h4');
let h1 = document.createElement('h1');
let color_div = document.querySelector('#color_div');
let createDiv;
h4.style.alignItems = 'center';
h4.append(h1);
let valueRGB = rgb();
h1.innerText = valueRGB.toUpperCase();
h1.style.alignItems = 'center';
first_div.style.backgroundColor = rgb();
function rgb() {
let r = Math.floor(Math.random() * 255 + 0);
let g = Math.floor(Math.random() * 255 + 0);
let b = Math.floor(Math.random() * 255 + 0);
return (`rgb(${r}, ${g}, ${b})`);
}
function threeRandomNumber() {
let threeRandomNumber = Math.floor(Math.random() * 3 + 1);
return threeRandomNumber;
}
function divCreate() {
createDiv = document.createElement('div');
createDiv.classList = 'dynamacily_create_div';
createDiv.style.backgroundColor = `${rgb()}`;
return createDiv;
}
function randomDiv() {
let color_fix = threeRandomNumber();
console.log('outter Background ' + color_fix);
for (let i = 0; i < 3; i++) {
let div_fix = threeRandomNumber();
if (div_fix === 1) {
color_div.appendChild(divCreate());
console.log('outter Background inner' + color_fix);
if (color_fix === 1) {
createDiv.style.backgroundColor = valueRGB;
console.log(valueRGB);
console.log('inner Background ' + color_fix);
}
} else if (div_fix === 2) {
color_div.appendChild(divCreate());
console.log('outter Background inner' + color_fix);
if (color_fix === 2) {
createDiv.style.backgroundColor = valueRGB;
console.log(valueRGB);
console.log('inner Background ' + color_fix);
}
} else {
color_div.appendChild(divCreate());
console.log('outter Background inner' + color_fix);
if (color_fix === 3) {
createDiv.style.backgroundColor = valueRGB;
console.log(valueRGB);
console.log('inner Background ' + color_fix);
}
}
}
}
randomDiv()
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
body {
display: flex;
justify-content: center;
}
h4,
h5 {
color: #ffffff;
font-size: 40px;
}
#first_div {
width: 900px;
height: 200px;
border: 1px solid red;
display: flex;
align-items: center;
flex-direction: column;
}
#color_div {
height: 400px;
width: 100%;
background-color: black;
display: flex;
flex-direction: row;
justify-content: center;
}
.dynamacily_create_div {
width: 200px;
height: 200px;
border-radius: 25px;
margin: 10px;
border: 1px solid red;
}
<body>
<main>
<div id="first_div">
<h4>THE GREAT</h4>
<h5>GUESSING GAME</h5>
</div>
<div id="second_div">
<button id="newColor">New Color</button>
<button id="playAgain">Play Again</button>
<button id="tryAgain">Try Again</button>
<button id="correct">Correct</button>
<button id="easy">Easy</button>
</div>
<div id="color_div">
</div>
</main>
<script src="app.js"></script>
</body>
Some logical branches are ignored by you.
Both div_fix and color_fix are returned by threeRandomNumber().
div_fix can be any one of [1,2,3].
color_fix can be any one of [1,2,3]. They can be the same or not.
While div_fix===1 and color_fix===2 , code is missing.
While div_fix===1 and color_fix===3 , code is missing.
Please check and fix your problem.
if (div_fix === 1) {
color_div.appendChild(divCreate());
console.log('outter Background inner' + color_fix);
if (color_fix === 1) {
createDiv.style.backgroundColor = valueRGB;
console.log(valueRGB);
console.log('inner Background ' + color_fix);
}else{
// Here!! maybe color_fix === 2 or color_fix === 3, Do sth.
}
}
We have used the TinyMCE editor with "non editable" plugin. we tried to delete the non editable content, it is deleted. How to restrict the delete(delete/backspace) action for non editable content?
Below is my code:
tinymce.init({
selector: "#myeditablediv",
plugins: "advlist table lists image paste link pagebreak noneditable help",
noneditable_noneditable_class: "mceNonEditable",
menubar: false,
inline: true,
height: 500,
paste_data_images: true,
toolbar_sticky: true,
toolbar:
"bold italic underline | superscript subscript | formatselect | bullist | code pagebreak | link image | COC | table | removeformat | help",
formats: {
editable: {
inline: "span",
styles: { borderBottom: "2px solid gray" },
classes: "mceEditable"
}
},
setup: function (editor) {
editor.ui.registry.addButton("COC", {
text: "<b style='font-size:large;font-weight:bold;'>{CC}</b>",
tooltip: "CopyToClipBoard",
onAction: function (api) {
editor.execCommand("Copy");
}
});
},
toolbar_mode: "floating"
});
.demo-inline {
box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.2);
text-align: left;
line-height: 1.3;
background-color: #ffffff;
text-align: left;
vertical-align: top;
padding: 20px 20px 20px 20px;
}
.demo-inline .container {
background-color: #fafafa;
margin: -20px -20px 0 -20px;
padding: 20px;
}
.demo-inline ul,
.demo-inline ol {
padding-left: 20px;
}
.demo-inline ul {
list-style: disc;
}
.demo-inline ol {
list-style: decimal;
}
.demo-inline a {
text-decoration: underline;
}
.demo-inline img {
display: block;
margin-left: auto;
margin-right: auto;
padding: 0px 10px 10px 10px;
}
.demo-inline textarea {
display: none;
}
.demo-inline *[contentEditable="true"]:focus,
.demo-inline *[contentEditable="true"]:hover {
outline: 2px solid #2276d2;
}
#myeditablediv {
margin-top: 20px;
font-family: "Calibri";
font-size: 16px;
line-height: 1.1em;
}
/*Component Editable*/
div.FixedComponent {
text-align: center;
background-color: #d8d8d8;
padding: 10px;
}
div.FixedComponent::before {
content: attr(data-displayname);
}
div[data-prefix]::before {
content: attr(data-prefix);
color: #1f477d !important;
font-weight: bold;
float: left;
display: inline-block;
margin-right: 3px;
}
.componentSuffix::after {
content: " ]";
color: #1f477d !important;
font-weight: bold;
}
div[data-type="content"] {
min-height: 23px;
display: inline;
}
div.ComponentWrapper:focus {
outline: dotted;
}
<script src="https://cdn.tiny.cloud/1/qagffr3pkuv17a8on1afax661irst1hbr4e6tbv888sz91jc/tinymce/5/tinymce.min.js"></script>
<div class="demo-inline">
<div id="myeditablediv">
Hi tiny
<p class='mceNonEditable'> <b> This is a non editable content</b>
</p>
<p> <span class='mceNonEditable'> <b>This part is non editable</b> </span>
This is a editable content
<span class='mceNonEditable'> <b>This part is non editable</b> </span>
</p>
</div>
</div>
TinyMCE's noneditable plugin is designed to make a block of content non-editiable, but not non-deletable. Rather it treats the entire section of non-editable content as a single character.
To stop content from being deleted with the keyboard, you could use Tiny's event handling structure to look for certain key presses and then interrupt/stop them. Here is a very simple example of how to do that:
http://fiddle.tinymce.com/Mvhaab
You would need to expand this to look at where the cursor is located in the content, and if the result of the keypress would delete something you want to preserve, stop the keypress only in those situations.
Note that this approach will not keep content from being deleted via other methods, such as by removing it as part of a larger selection.
Wrote an Angular service which so far works alright, possibly needs some tweaking for edge cases. nonDeletableSelectors contains the CSS selectors denoting elements which should be non-deletable. I noticed that there is apparently a TinyMCE bug with non-editable elements though, so the code is more complex than I think it should be.
import {Injectable} from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class EditorPreventDeleteService {
constructor() { }
public nonDeletableSelectors = ['.mceNonEditable'];
public preventDelete(editor) {
let self = this;
editor.on('keydown', function(event) {
if (self.keyWillDelete(event)) {
let range = editor.selection.getRng(), selection = editor.selection.getSel();
if (!range.collapsed)
return self.checkSelection(editor, event);
else if (event.keyCode == 8)
self.checkBackspace(editor, event, selection);
else if (event.keyCode == 46)
self.checkDelete(editor, event, selection);
}
return true;
});
editor.on('beforeSetContent', event => {
return self.checkSelection(editor, event);
});
editor.on('dragstart', event => {
if (self.checkNode(event.target, true))
self.cancelEvent(event);
});
}
protected checkNode(node, includeChildren = true) {
if (node && node.nodeType !== Node.TEXT_NODE)
for (let nonDeletableSelector of this.nonDeletableSelectors)
if (node.matches(nonDeletableSelector)
|| (includeChildren && node.querySelectorAll(nonDeletableSelector).length > 0))
return true;
return false;
}
protected checkSelection(editor, event) {
const selectedHTMLString = editor.selection.getContent({format : 'html'});
const selectedHTML = new DOMParser().parseFromString(selectedHTMLString, 'text/html').documentElement;
if (this.checkNode(selectedHTML))
return this.cancelEvent(event);
return true;
}
protected checkBackspace(editor, event, selection) {
if (selection.anchorOffset === 0 && this.getPrefixContent(editor, selection).length === 0)
return this.cancelEvent(event);
this.checkCaretDeletion(editor, event, selection, false);
}
protected checkDelete(editor, event, selection) {
this.checkCaretDeletion(editor, event, selection, true);
}
protected checkCaretDeletion(editor, event, selection, forwards = true) { // https://developer.mozilla.org/en-US/docs/Web/API/Selection
let borderingElement = forwards ? selection.anchorNode.nextSibling : selection.anchorNode.previousSibling;
if (selection.anchorNode.nodeType === Node.TEXT_NODE) {
if (this.getTrailingText(selection, forwards, false).length > 0)
return; // not at the border of a text element
} else if (selection.anchorOffset !== (forwards ? selection.anchorNode.childNodes.length : 0)
&& this.trimZeroWidthSpaces(selection.anchorNode.textContent).length > 0
&& this.checkNode(selection.anchorNode.childNodes.item(selection.anchorOffset + (forwards?0:1))))
return this.cancelEvent(event); // not at the border of anchor, anchor not empty, only neighbouring child is deleted
if (this.checkNode(selection.anchorNode) || this.checkNode(borderingElement))
this.cancelEvent(event);
}
protected getPrefixContent(editor, selection) {
let currentRange = editor.selection.getRng(1), tempRange = currentRange.cloneRange();
tempRange.setStartBefore(editor.getBody().childNodes.item(0));
tempRange.setEndBefore(selection.anchorNode);
editor.selection.setRng(tempRange);
let content = editor.selection.getContent({format: 'html'});
editor.selection.setRng(currentRange);
return this.trimZeroWidthSpaces(content.trim());
}
protected getTrailingText(selection, forwards = true, includeSiblings = false) {
let trailer = '', appendTrailer = function(text) { forwards ? trailer += text : trailer = text + trailer; }
if (selection.anchorNode.nodeType === Node.TEXT_NODE) {
let text = selection.anchorNode.textContent;
appendTrailer(forwards ? text.substr(selection.anchorOffset) : text.substr(0, selection.anchorOffset));
} else {
for (let i=selection.anchorOffset ; i>=0 && i<selection.anchorNode.childNodes.length ; i+=(forwards?-1:1))
appendTrailer(selection.anchorNode.childNodes.item(i).textContent);
}
if (includeSiblings) {
let sibling = selection.anchorNode.previousSibling;
while (sibling) {
appendTrailer(sibling.textContent);
sibling = sibling.previousSibling;
}
}
return this.trimZeroWidthSpaces(trailer);
}
protected cancelEvent(event) {
event.preventDefault();
event.stopPropagation();
return false;
}
protected keyWillDelete(evt) {
let c = evt.keyCode;
if (evt.ctrlKey)
return evt.key == 'x' || [8, 46].includes(c);
return [8, 9, 13, 46].includes(c)
|| this.inRange(c, 48, 57)
|| this.inRange(c, 65, 90)
|| this.inRange(c, 96, 111)
|| this.inRange(c, 186, 192)
|| this.inRange(c, 219, 222);
}
protected inRange(val, min, max) {
return val >= min && val <= max;
}
protected trimZeroWidthSpaces(text: string) {
return text.replace(/[\u200B-\u200D\uFEFF]/g, '');
}
}
I created a basic voting system for a comment ratings bar. I'm trying to access the previous Sibling Element to update the votes but it's not working properly. IAre you're supposed to use event.currentTarget or event.target? Where did I go wrong? Thank you.
https://jsfiddle.net/donfontaine12/bm9njcLt/46/#&togetherjs=qocecyJqyy
HTML
<div id="comment_ratings_bar">
<div id="comment_rating_sign">+</div>
<div id="comment_rating_num">0</div>
<div id="comment_rating_percentage">[100.00%] </div>
<div class="green_up_arrow"></div>
<div class="red_down_arrow"></div>
</div>
<div id="comment_ratings_bar">
<div id="comment_rating_sign">+</div>
<div id="comment_rating_num">0</div>
<div id="comment_rating_percentage">[100.00%] </div>
<div class="green_up_arrow"></div>
<div class="red_down_arrow"></div>
</div>
<div id="comment_ratings_bar">
<div id="comment_rating_sign">+</div>
<div id="comment_rating_num">0</div>
<div id="comment_rating_percentage">[100.00%] </div>
<div class="green_up_arrow"></div>
<div class="red_down_arrow"></div>
</div>
<div id="comment_ratings_bar">
<div id="comment_rating_sign">+</div>
<div id="comment_rating_num">0</div>
<div id="comment_rating_percentage">[100.00%] </div>
<div class="green_up_arrow"></div>
<div class="red_down_arrow"></div>
</div>
CSS
#comment_ratings_bar {
width: 30%;
margin: 0px 20px;
padding: 0px 20px;
font-size: 110%;
font-weight: bolder;
font-family: 'B612 Mono', monospace;
color: lime;
background-color: black;
border: 0px solid black;
display: flex;
flex-direction: row;
justify-content: center;
}
.green_up_arrow {
display: flex;
flex-direction: row;
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 10px solid lime;
cursor: pointer;
margin: 0em 0.25em;
}
.red_down_arrow {
display: flex;
flex-direction: row;
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 10px solid red;
cursor: pointer;
margin: 0em 0.25em;
}
JavaScript
window.onload = function() {
let commentUpvotes = 0;
let commentDownvotes = 0;
let totalCommentVotes = commentUpvotes + commentDownvotes;
let commentRatingsBarAll = document.querySelectorAll("#comment_ratings_bar");
for (let c of commentRatingsBarAll) {
c.lastElementChild.previousElementSibling.addEventListener("click", updateCommentVotes);
c.lastElementChild.addEventListener("click", updateCommentVotes);
}
function updateCommentVotes(e) {
let siblings = getSiblings(e);
let sign = siblings[0].textContent;
let number = siblings[1].textContent;
let percentage = siblings[2].textContent;
if (sign && number && percentage) {
let actualNumber = parseFloat(number.replace(/,/g, ''));
if (e.target.className == "green_up_arrow") {
actualNumber++; commentUpvotes++; totalCommentVotes++;
} else {
actualNumber--; commentDownvotes++; totalCommentVotes++;
}
if (actualNumber < 0) { sign.replace("+", ""); }
percentage = "["
+ parseFloat((commentUpvotes / totalCommentVotes) * 100).toFixed(2) +"%]";
number = actualNumber.toLocaleString();
}
}
function getSiblings(element) {
if (element) {
let siblings = [];
let sibling = element.parentNode.firstElementChild;
while(sibling) {
if (sibling.nodeType === 1 && sibling !== element) {
siblings.push(sibling);
sibling = sibling.nextElementSibling;
}
}
return siblings;
}
}
}
Everything's working but inside the updateCommentVotes function, I should have been referencing the actual divs containing the textContent instead of the local variables (sign, number & percentage).
EDIT: It's a partial fix, I need each individual comment bar to refer to its own sign, number and percentage. It seems they all share the same number values. Any tips are appreciated. Although, I believe its because I hard coded the values from siblings. Thank you.
Check the code here: https://jsfiddle.net/donfontaine12/bm9njcLt/46/#
JavaScript
window.onload = function() {
let commentUpvotes = 0;
let commentDownvotes = 0;
let totalCommentVotes = commentUpvotes + commentDownvotes;
let commentRatingsBarAll = document.querySelectorAll("#comment_ratings_bar");
for (let c of commentRatingsBarAll) {
c.lastElementChild.previousElementSibling.addEventListener("click", updateCommentVotes);
c.lastElementChild.addEventListener("click", updateCommentVotes);
}
function updateCommentVotes(e) {
let siblings = getSiblings(e);
let sign = siblings[0].textContent;
let number = siblings[1].textContent;
let percentage = siblings[2].textContent;
if (sign && number && percentage) {
let actualNumber = parseFloat(number.replace(/,/g, ''));
if (e.target.className == "green_up_arrow") {
actualNumber++; commentUpvotes++; totalCommentVotes++;
} else {
actualNumber--; commentDownvotes++; totalCommentVotes++;
}
if (actualNumber < 0) { siblings[0].textContent.replace("+", ""); }
siblings[2].textContent = "["
+ parseFloat((commentUpvotes / totalCommentVotes) * 100).toFixed(2) +"%]";
siblings[1].textContent = actualNumber.toLocaleString();
}
}
function getSiblings(element) {
let siblings = [];
let sibling = element.target.parentNode.firstElementChild;
while(sibling) {
if (sibling.nodeType === 1 && sibling !== element) {
siblings.push(sibling);
sibling = sibling.nextElementSibling;
}
}
return siblings;
}
}
I will try this one more time.
I am having trouble getting the quote to download as part of the sketch canvas. I am using sketch.js.
Here is the jsfiddle, you can draw like MSpaint but I when pressing the download button only what is drawn is copied. I would like the sketch and the words downloaded.
http://jsfiddle.net/e1ovm9mn/
I should also add that I am quite new to all.
Here is the code
<body>
<nav>
<div id="SketchTools">
<!-- Basic tools -->
<img src="img/black_icon.png" alt="Black"/>
<img src="img/red_icon.png" alt="Red"/>
<img src="img/green_icon.png" alt="Green"/>
<img src="img/blue_icon.png" alt="Blue"/>
<img src="img/yellow_icon.png" alt="Yellow"/>
<img src="img/cyan_icon.png" alt="Cyan"/>
<!-- Advanced colors -->
<img src="img/alizarin_icon.png" alt="Alizarin"/>
<img src="img/pomegrante_icon.png" alt="Pomegrante"/>
<img src="img/emerald_icon.png" alt="Emerald"/>
<img src="img/torquoise_icon.png" alt="Torquoise"/>
<img src="img/peterriver_icon.png" alt="Peter River"/>
<img src="img/amethyst_icon.png" alt="Amethyst"/>
<img src="img/sunflower_icon.png" alt="Sun Flower"/>
<img src="img/orange_icon.png" alt="Orange"/>
<img src="img/clouds_icon.png" alt="Clouds"/>
<img src="img/silver_icon.png" alt="Silver"/>
<img src="img/asbestos_icon.png" alt="Asbestos"/>
<img src="img/wetasphalt_icon.png" alt="Wet Asphalt"/>
</br> <img src="img/eraser_icon.png" alt="Eraser"/>
<!-- Size options -->
<img src="img/pencil_icon.png" alt="Pencil"/>
<img src="img/pen_icon.png" alt="Pen"/>
<img src="img/stick_icon.png" alt="Stick"/>
<img src="img/smallbrush_icon.png" alt="Small brush"/>
<img src="img/mediumbrush_icon.png" alt="Medium brush"/>
<img src="img/bigbrush_icon.png" alt="Big brush"/>
<img src="img/bucket_icon.png" alt="Huge bucket"/>
Download
<br/>
</div>
<div class="links">
<ul>
<li><img src="ficon.png" alt="Facebook"></li>
<li><img src="igramicon.png" alt="Instagram"></li>
<li><img src="picon.png" alt="Pinterest"></li>
<li><img src="mcicon.png" alt="Mixcloud"></li>
<li><img src="twicon.png" alt="Twitter"></li>
</ul>
</div>
<div class="message">
<div id="quote"></div>
<script>
(function() {
var quotes = [
{ text: "Snuggletooth likes pancakes"},
{ text: "Would you like Snuggletooth to tuck you in?"},
{ text: " Snuggletooth loves you"},
{ text: "Snuggletooth is here for you"},
{ text: "Did you know that Snuggletooth </br>can be in 2 places at once?"},
{ text: "Heyyyy!<br> I was just thinking about you </br>Love Snuggletooth" },
{ text: "Wanna Sandwich??</br>xSnuggletooth"},
{ text: "Want some breakfast???</br> ;) Snuggletooth"},
{ text: "Snuggletooth-a-riffic!!!"},
{ text: "Snuggletooth makes great popcorn!"},
{ text: "Come over to Snuggletooth's! He makes a great guacamole!"},
{ text: "Snuggletooth likes his bubblebaths to smell like bubblegum"},
{ text: "Snuggletooth wants to know what are you up to later?"},
{ text: "Snuggletooth-a-licious!!!"},
];
var quote = quotes[Math.floor(Math.random() * quotes.length)];
document.getElementById("quote").innerHTML =
'<p>' + quote.text + '</p>' +
'' + '';
})();
</script>
</div>
</nav>
<canvas id="SketchPad" width="1125" height="600">
</canvas>
</div>
<script type="text/javascript">
$(function() {
$('#SketchPad').sketch();
});
</script>
</body>
And here is the sketch.js
var __slice = Array.prototype.slice;
(function($) {
var Sketch;
$.fn.sketch = function() {
var args, key, sketch;
key = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (this.length > 1) {
$.error('Sketch.js can only be called on one element at a time.');
}
sketch = this.data('sketch');
if (typeof key === 'string' && sketch) {
if (sketch[key]) {
if (typeof sketch[key] === 'function') {
return sketch[key].apply(sketch, args);
} else if (args.length === 0) {
return sketch[key];
} else if (args.length === 1) {
return sketch[key] = args[0];
}
} else {
return $.error('Sketch.js did not recognize the given command.');
}
} else if (sketch) {
return sketch;
} else {
this.data('sketch', new Sketch(this.get(0), key));
return this;
}
};
Sketch = (function() {
function Sketch(el, opts) {
this.el = el;
this.canvas = $(el);
this.context = el.getContext('2d');
this.options = $.extend({
toolLinks: true,
defaultTool: 'marker',
defaultColor: 'black',
defaultSize: 5
}, opts);
this.painting = false;
this.color = this.options.defaultColor;
this.size = this.options.defaultSize;
this.tool = this.options.defaultTool;
this.actions = [];
this.action = [];
this.canvas.bind('click mousedown mouseup mousemove mouseleave mouseout touchstart touchmove touchend touchcancel', this.onEvent);
if (this.options.toolLinks) {
$('body').delegate("a[href=\"#" + (this.canvas.attr('id')) + "\"]", 'click', function(e) {
var $canvas, $this, key, sketch, _i, _len, _ref;
$this = $(this);
$canvas = $($this.attr('href'));
sketch = $canvas.data('sketch');
_ref = ['color', 'size', 'tool'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
key = _ref[_i];
if ($this.attr("data-" + key)) {
sketch.set(key, $(this).attr("data-" + key));
}
}
if ($(this).attr('data-download')) {
sketch.download($(this).attr('data-download'));
}
return false;
});
}
}
Sketch.prototype.download = function(format) {
var mime;
format || (format = "png");
if (format === "jpg") {
format = "jpeg";
}
mime = "image/" + format;
return window.open(this.el.toDataURL(mime));
};
Sketch.prototype.set = function(key, value) {
this[key] = value;
return this.canvas.trigger("sketch.change" + key, value);
};
Sketch.prototype.startPainting = function() {
this.painting = true;
return this.action = {
tool: this.tool,
color: this.color,
size: parseFloat(this.size),
events: []
};
};
Sketch.prototype.stopPainting = function() {
if (this.action) {
this.actions.push(this.action);
}
this.painting = false;
this.action = null;
return this.redraw();
};
Sketch.prototype.onEvent = function(e) {
if (e.originalEvent && e.originalEvent.targetTouches) {
e.pageX = e.originalEvent.targetTouches[0].pageX;
e.pageY = e.originalEvent.targetTouches[0].pageY;
}
$.sketch.tools[$(this).data('sketch').tool].onEvent.call($(this).data('sketch'), e);
e.preventDefault();
return false;
};
Sketch.prototype.redraw = function() {
var sketch;
this.el.width = this.canvas.width();
this.context = this.el.getContext('2d');
sketch = this;
$.each(this.actions, function() {
if (this.tool) {
return $.sketch.tools[this.tool].draw.call(sketch, this);
}
});
if (this.painting && this.action) {
return $.sketch.tools[this.action.tool].draw.call(sketch, this.action);
}
};
return Sketch;
})();
$.sketch = {
tools: {}
};
$.sketch.tools.marker = {
onEvent: function(e) {
switch (e.type) {
case 'mousedown':
case 'touchstart':
this.startPainting();
break;
case 'mouseup':
case 'mouseout':
case 'mouseleave':
case 'touchend':
case 'touchcancel':
this.stopPainting();
}
if (this.painting) {
this.action.events.push({
x: e.pageX - this.canvas.offset().left,
y: e.pageY - this.canvas.offset().top,
event: e.type
});
return this.redraw();
}
},
draw: function(action) {
var event, previous, _i, _len, _ref;
this.context.lineJoin = "round";
this.context.lineCap = "round";
this.context.beginPath();
this.context.moveTo(action.events[0].x, action.events[0].y);
_ref = action.events;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
event = _ref[_i];
this.context.lineTo(event.x, event.y);
previous = event;
}
this.context.strokeStyle = action.color;
this.context.lineWidth = action.size;
return this.context.stroke();
}
};
return $.sketch.tools.eraser = {
onEvent: function(e) {
return $.sketch.tools.marker.onEvent.call(this, e);
},
draw: function(action) {
var oldcomposite;
oldcomposite = this.context.globalCompositeOperation;
this.context.globalCompositeOperation = "copy";
action.color = "rgba(0,0,0,0)";
$.sketch.tools.marker.draw.call(this, action);
return this.context.globalCompositeOperation = oldcomposite;
}
};
})(jQuery);
And just in case here is the css
#import url(http://fonts.googleapis.com/css?family=Codystar);
#import url(http://fonts.googleapis.com/css?family=Lobster);
img {
width: 25px;
height: 25px;
}
li{
}
ul li {
list-style-type: none;
display: inline;
}
.message {
margin-left: 20%;
margin-top: 20%;
z-index: 1;
position: absolute;
font-family: Lobster, Codystar, arial;
font-size: 3.5em;
color:white;
text-align: center;
text-shadow: 2px 2px #ff0000;
}
.links {
float: right;
padding-right: 1em;
}
#SketchPad {
border-color: black;
border-width: 3px;
border-style: solid;
position: fixed;
}
#DownloadPng {
padding: 4px 2px;
font-size: 1em;
line-height: 100%;
text-shadow: 0 1px rgba(0, 0, 0, 0.5);
color: #fff;
display:inline-block;
/*vertical-align: middle;
text-align: center;*/
cursor: pointer;
font-weight: bold;
transition: background 0.1s ease-in-out;
-webkit-transition: background 0.1s ease-in-out;
-moz-transition: background 0.1s ease-in-out;
-ms-transition: background 0.1s ease-in-out;
-o-transition: background 0.1s ease-in-out;
text-shadow: 0 1px rgba(0, 0, 0, 0.3);
color: #fff;
font-family: Arial, sans-serif;
background-color: #2ecc71;
box-shadow: 0px 7px 0px 0px #27ae60;
text-decoration: none;
margin-top: 10px;
margin-bottom: 15px;
}
#DownloadPng:hover {
background-color: #27ae60;
border-radius: 7px;
}
#DownloadPng:active {
box-shadow: 0px 1px 0px 0px #27ae60;
border-radius: 7px;
}
#SketchTools {
width: 65%;
height: 5%;
position: fixed;
float: left;
z-index: 1;
padding: .2em;
}
I have been writing my own Lightbox script (to learn more about jQuery).
My code for the captions are as follows (the problem is that the captions are the same on every image):
close.click(function(c) {
c.preventDefault();
if (hideScrollbars == "1") {
$('body').css({'overflow' : 'auto'});
}
overlay.add(container).fadeOut('normal');
$('#caption').animate({
opacity: 0.0
}, "5000", function() {
$('div').remove('#caption');
});
});
$(prev.add(next)).click(function(c) {
c.preventDefault();
$('div').remove('#caption')
areThereAlts = "";
var current = parseInt(links.filter('.selected').attr('lb-position'),10);
var to = $(this).is('.prev') ? links.eq(current - 1) : links.eq(current + 1);
if(!to.size()) {
to = $(this).is('.prev') ? links.eq(links.size() - 1) : links.eq(0);
}
if(to.size()) {
to.click();
}
});
So, I found out what was wrong (Cheers Deng!), further down the code I had the following function (I had to add "link" into the remove caption code):
links.each(function(index) {
var link = $(this);
link.click(function(c) {
c.preventDefault();
if (hideScrollbars == "1") {
$('body').css({'overflow' : 'hidden'});
}
open(link.attr('href'));
links.filter('.selected').removeClass('selected');
link.addClass('selected');
var areThereAlts = $(".thumb", link).attr("alt"); //"link" needed to be added here
//alert(areThereAlts);
if (areThereAlts !== "") {
container.append('<div id="caption" style="display: block; font-family: Verdana; background-color: white; padding: 4px 5px 10px 5px; top -10px; width: 100%; height: 25px; vertical-align: middle; -moz-border-radius-topleft: 10px; -moz-border-radius-topright: 10px; color: #3f3f3f;"><font color="#3f3f3f">'+areThereAlts+'</font></div>') //caption
}
});
link.attr({'lb-position': index});
});