TinyMCE 4.x count character - javascript

I trying to create character count on tiny mce 4.x. I create counter but I can limit user to type.
tinymce.init({
selector:'textarea',
charLimit : 20, // this is a default value which can get modified later
setup: function(editor) {
editor.on('KeyUp', function(e) {
var tinymax, tinylen, htmlcount;
tinymax = this.settings.charLimit;
tinylen = this.getContent().length;
$("#charNum").html(tinylen);
if (tinylen > tinymax) {
$("#charNum").html(tinylen);
// STOP TYPE
}
});
}
});
I add e.preventDefault(); but now user can not delete input
if (tinylen > tinymax) {
$("#charNum").html(tinylen);
e.preventDefault();
}

Here is an example:
var max = 5;
$('#a').on('keyup', function(){
var val = $(this).val();
if( val.length > max ){
$(this).val(val.substr(val, max));
}
});
So, if the input length is higher than maximum permitted, just cut it.
Check the jsFiddle

Related

Add Class to div when click counter reaches 0

Right now when you click inside the div, the counter decreases by 1. How do I make it stop at 0?
Also when it reaches 0 how can I add a class?
I want the overlay to be enabled once the click counter reaches 0.
If there is a better way to disable the div box1 after the clicks reach 0. We can try it that way.
$( function() {
$('.box').click( function() {
var num = $(this).find('.num');
num.text( parseInt(num.text()) - 1 );
});
});
fiddle
Rather than searching DOM and parsing HTML on each click, I'd cache both element and its value:
var $box = $('#box1'),
$num = $box.find('.num'),
limit = $num.text();
$box.click(function() {
$num.text(--limit);
if (limit === 0) {
$('.overlay').show();
}
});
Demo.
This should do it:
$('.box').click( function() {
var num = $(this).find('.num');
val = parseInt(num.text()) - 1;
if (val > 0){
num.text(val - 1);
} else {
$(".overlay").show();
// add your class here.
}
num.text( val );
});
Updated Fiddle

How to increase and decrease a counter from one button - click and click again jQuery

This is the code that I am currently using:
<script>
$(".lk").click(function(){
$(this).find("#lke").html(function(i, val) { return val*1+1 });
});
$(".lk").click(function(){
$(this).find("#lke").html(function(i, val) { return val*1-1 });
});
</script>
When the user clicks on the button, the value of #lke increases by 1. When he clicks again, the value decreases by 1. The code that I am currently using does not work so how would I fix this?
You can use an external var to decide if you have to increment o decrement the value
<script>
var increment = true;
$(".lk").click(function(){
var lke = $(this).find("#lke"),
value = parseInt(lke.html()) || 0;
lke.html( increment ? value + 1 : value - 1);
increment = !increment;
});
</script>
Your code doesn't work because you assign two events for every click - one which increases the value and one which decreases it, so nothing happens.
You could use an external variable such as toAdd to determine which action to do:
var toAdd = 1;
$(".lk").click(function(){
newValue = oldValue + toAdd;
toAdd *= -1;
...
});
You put two call of the same object, try this instead
<script>
var val = 0; // Put the original value
var negative = false;
$( document ).ready(function() { // You need to declare document ready
$(".lk").click(function(){
val = val + ((negative) ? -1 : 1); // Change if its positive or negative
negative = (negative) ? false : true;
$("#lke").text(val); // Adjust the html ?
});
});
</script>
Try something like this:
$(".lk").click(function() {
if ($(this).hasClass('clicked')) {
$(this).removeClass('clicked'));
$(this).find("#lke").html(function(i, val) { return val*1-1 });
} else {
$(this).addClass('clicked');
$(this).find("#lke").html(function(i, val) { return val*1+1 });
}
});
You could also use a data attribute instead of checking for a class aswell.
Or use toggleClass().
$(".lk").click(function() {
if ($(this).hasClass('clicked')) {
$(this).toggleClass('clicked'));
$(this).find("#lke").html(function(i, val) { return val*1-1 });
} else {
$(this).toggleClass('clicked');
$(this).find("#lke").html(function(i, val) { return val*1+1 });
}
});

.each function () for cloned inputs

Trying to create the Preview form and do not understand why each function () not working in this script. Or works but only for the last cloned row and ignore the zero values ​​in the previously cloned inputs.
$('input[id^=Mult_factor_]').each(function () {
var MultFactor = $(this).val();
var TotPoints = $('#Tot_points').val();
var exp1 = "Overload";
var exp2 = "Load is: ";
if (MultFactor < 1 || TotPoints > 100) {
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
JSfiddle
I need: If at least one of cloned MultiFactor value is zero show "Overload"
Based on your comment, you want to display the word "Overload" if either the "Additional" field is over 100 or if any of the multifactor fields is 0.
However, your loop continues to process if either of these conditions are met.
Do not use a loop, instead search specifically for a multifaktor value of 0.
var totalPoints = parseInt($('#Tot_points').val());
if(totalPoints > 100 || $('input[name="MultFaktor"]').filter(function(){return this.value=='0'}).length > 0) {
$('#ExemptionLimitsText').text("Overload").show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text("Load is: ").show();
$('#PrwTotPointsText').text(totalPoints).show();
}
Return false on overload
var valid = true;
var exp1 = "Overload";
var exp2 = "Load is: ";
var TotPoints = $('#Tot_points').val();
$('input[name=MultFaktor]').each(function () {
var $this = $(this);
if ($.trim($(this).val()) == '0' || TotPoints > 100) {
valid = false;
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
if (valid == false) {
e.preventDefault();
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
}

How do I listen for triple clicks in JavaScript?

If this is for a double-click:
window.addEventListener("dblclick", function(event) { }, false);
How can I capture a triple-click? This is for a pinned tab in Google Chrome.
You need to write your own triple-click implementation because no native event exists to capture 3 clicks in a row. Fortunately, modern browsers have event.detail, which the MDN documentation describes as:
A count of consecutive clicks that happened in a short amount of time, incremented by one.
This means you can simply check the value of this property and see if it is 3:
window.addEventListener('click', function (evt) {
if (evt.detail === 3) {
alert('triple click!');
}
});
Working demo: http://jsfiddle.net/L6d0p4jo/
If you need support for IE 8, the best approach is to capture a double-click, followed by a triple-click β€” something like this, for example:
var timer, // timer required to reset
timeout = 200; // timer reset in ms
window.addEventListener("dblclick", function (evt) {
timer = setTimeout(function () {
timer = null;
}, timeout);
});
window.addEventListener("click", function (evt) {
if (timer) {
clearTimeout(timer);
timer = null;
executeTripleClickFunction();
}
});
Working demo: http://jsfiddle.net/YDFLV/
The reason for this is that old IE browsers will not fire two consecutive click events for a double click. Don't forget to use attachEvent in place of addEventListener for IE 8.
Since DOM Level 2 you could use mouse click handler and check the detail parameter of event which should be interpreted as:
The detail attribute inherited from UIEvent indicates the number of times a mouse button has been pressed and released over the same screen location during a user action. The attribute value is 1 when the user begins this action and increments by 1 for each full sequence of pressing and releasing. If the user moves the mouse between the mousedown and mouseup the value will be set to 0, indicating that no click is occurring.
So the value of detail === 3 will give you the triple-click event.
More information in specification at http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-MouseEvent.
Thanks to #Nayuki https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail - a DOM3 extension which is WIP https://w3c.github.io/uievents/
Here is the real Triple click event, which triggers only when all of three clicks fired with equal interval.
// Default settings
var minClickInterval = 100,
maxClickInterval = 500,
minPercentThird = 85.0,
maxPercentThird = 130.0;
// Runtime
var hasOne = false,
hasTwo = false,
time = [0, 0, 0],
diff = [0, 0];
$('#btn').on('click', function() {
var now = Date.now();
// Clear runtime after timeout fot the 2nd click
if (time[1] && now - time[1] >= maxClickInterval) {
clearRuntime();
}
// Clear runtime after timeout fot the 3rd click
if (time[0] && time[1] && now - time[0] >= maxClickInterval) {
clearRuntime();
}
// Catch the third click
if (hasTwo) {
time[2] = Date.now();
diff[1] = time[2] - time[1];
var deltaPercent = 100.0 * (diff[1] / diff[0]);
if (deltaPercent >= minPercentThird && deltaPercent <= maxPercentThird) {
alert("Triple Click!");
}
clearRuntime();
}
// Catch the first click
else if (!hasOne) {
hasOne = true;
time[0] = Date.now();
}
// Catch the second click
else if (hasOne) {
time[1] = Date.now();
diff[0] = time[1] - time[0];
(diff[0] >= minClickInterval && diff[0] <= maxClickInterval) ?
hasTwo = true : clearRuntime();
}
});
var clearRuntime = function() {
hasOne = false;
hasTwo = false;
time[0] = 0;
time[1] = 0;
time[2] = 0;
diff[0] = 0;
diff[1] = 0;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click button three times with equal interval
<button id="btn">Click me</button>
Also, I wrote jquery plugin TrplClick, which enables 'trplclick' event
it's very simple if you do it right, and you can even catch single, double, triple, ... clicks as you like. plain javascript, customizable click delay (timeout):
var clicks = 0;
var timer, timeout = 350;
var doubleClick = function(e) {
console.log('doubleClick');
}
var tripleClick = function(e) {
console.log('tripleClick');
}
// click timer
yourcontainer.addEventListener('click', function(e) {
clearTimeout(timer);
clicks++;
var evt = e;
timer = setTimeout(function() {
if(clicks==2) doubleClick(evt);
if(clicks==3) tripleClick(evt);
clicks = 0;
}, timeout);
});
pseudo-code:
var clicks = 0
onclick:
clicks++;
setTimer(resetClicksToZero);
if clicks == 3: tripleclickdetected(); clicks = 0;
I am working on a javascript code editor and I had to listen for triple click and here is the solution that will work for most browsers:
// Function to get mouse position
var getMousePosition = function (mouseEvent) {
var currentObject = container;
var currentLeft = 0;
var currentTop = 0;
do {
currentLeft += currentObject.offsetLeft;
currentTop += currentObject.offsetTop;
currentObject = currentObject.offsetParent;
} while (currentObject != document.body);
return {
x: mouseEvent.pageX - currentLeft,
y: mouseEvent.pageY - currentTop
}
}
// We will need a counter, the old position and a timer
var clickCounter = 0;
var clickPosition = {
x: null,
y: null
};
var clickTimer;
// The listener (container may be any HTML element)
container.addEventListener('click', function (event) {
// Get the current mouse position
var mousePosition = getMousePosition(event);
// Function to reset the data
var resetClick = function () {
clickCounter = 0;
var clickPosition = {
x: null,
y: null
};
}
// Function to wait for the next click
var conserveClick = function () {
clickPosition = mousePosition;
clearTimeout(clickTimer);
clickTimer = setTimeout(resetClick, 250);
}
// If position has not changed
if (clickCounter && clickPosition.x == mousePosition.x && clickPosition.y == mousePosition.y) {
clickCounter++;
if (clickCounter == 2) {
// Do something on double click
} else {
// Do something on triple click
resetClick();
}
conserveClick();
} else {
// Do something on single click
conserveClick();
}
});
Tested on Firefox 12, Google Chrome 19, Opera 11.64, Internet Explorer 9
This approach checks if the user has not changed cursor's position, you still can do something when you have single click or double click. Hope this solution will help everybody who will need to implement a triple click event listener :)
Configurable n-clicks event detector factory
const nClicks = (minClickStreak, maxClickInterval = 500, resetImmediately = true) => {
let timerId = 0
let clickCount = 0
let lastTarget = null
const reset = () => {
timerId = 0
clickCount = 0
lastTarget = null
}
return (originalEventHandler) => (e) => {
if (lastTarget == null || lastTarget == e.target) { // 2. unless we clicked same target
clickCount++ // 3. then increment click count
clearTimeout(timerId)
}
lastTarget = e.target
timerId = setTimeout(reset, maxClickInterval) // 1. reset state within set time
if (clickCount >= minClickStreak) {
originalEventHandler(e)
if (resetImmediately) {
clickCount = 0
}
}
}
}
Usage
table.addEventListener('click', nClicks(2)(e => { // double click
selectCell(e.target)
}))
table.addEventListener('click', nClicks(3)(e => { // triple click
selectRow(e.target)
}))

how do not duplicate a action in jquery

js:
$(".test").focusout(function(){
var qtdCont = parseInt($(this).val());
if(qtdCont > 0)
{
var qtdProd = $(".value").val();
var qtdProdInt = parseInt(qtdProd);
var qtdProdTot = qtdProd-qtdCont;
$(".value").val(qtdProdTot);
}
});
Demo: Jsfiddle
i need the subtract only the fist time when he lose the focus.
because if u go's back and focusout again, the subtraction (obviously) will happen again.
how can i control that ?
thank you.
Use the data in the dom element:
$(".test").focusout(function(){
var qtdCont = parseInt($(this).val());
if(qtdCont > 0 && $(this).data('done') == undefined)
{
var qtdProd = $(".value").val();
var qtdProdInt = parseInt(qtdProd);
var qtdProdTot = qtdProd-qtdCont;
$(".value").val(qtdProdTot);
$(this).data('done', true);
}
});
Fiddle: http://jsfiddle.net/dNEmD/19/
UPDATE
$(".test").focusout(function(){
var qtdCont = parseInt($(this).val());
if(qtdCont > 0 &&
($(this).data('done') == undefined || $(this).data('done') == false))
{
var qtdProd = $(".value").val();
var qtdProdInt = parseInt(qtdProd);
var qtdProdTot = qtdProd-qtdCont;
$(".value").val(qtdProdTot);
$(this).data('done', true);
}
});
$(".test").change(function(){ //if value was changed
$(this).data('done', false);
});
Fiddle: http://jsfiddle.net/dNEmD/27/
keep a semaphore variable at the top somewhere. It's start out false, then the first time you focus out set it true. It remains true for the rest of the programs lifespan and you do not allow certain parts of focusout code to execute when the semaphore variable is true.

Categories