How can I make my character countdown reset back to 150 when my submit button is clicked? Right now I have a input text box that you type in and it counts down how many characters you have left and then when you want to submit it, you click the submit button and it adds it to a table. But the problem is that the number stays the same and doesn't reset back to 150 until you start typing in the box again. I want it to automatically reset to 150 when you click the submit button. What will I need to add to my code?
http://jsfiddle.net/julianbuscema/qv0zd8pv/
$(document).ready(function(){
var left = 150
$('#text_counter').text(left);
$('#status').keyup(function () {
left = 150 - $(this).val().length;
if(left < 0){
$('#text_counter').addClass("overlimit");
}
if(left >= 0){
$('#text_counter').removeClass("overlimit");
}
$('#text_counter').text(left);
});
});
just re declare it
var btn = document.getElementsByTagName("button")[0];
var inpt = document.getElementsByName("post")[0];
btn.onclick = function () {
if (!inpt.value) alert("Please enter something to post.");
if (inpt.value.length < 10) {
alert("Post must be at least 10 characters.");
return false;
} else {
}
var tbl = document.getElementsByTagName("table")[0];
var row = tbl.insertRow(0);
var cell = row.insertCell(0);
var txt = document.createTextNode(inpt.value);
cell.appendChild(txt);
tbl.insertRow(0);
tbl.insertRow(0);
inpt.value = "";
$('#text_counter').text(150);
};
$(document).ready(function(){
var left = 150
$('#text_counter').text(left);
$('#status').keyup(function () {
left = 150 - $(this).val().length;
if(left < 0){
$('#text_counter').addClass("overlimit");
}
if(left >= 0){
$('#text_counter').removeClass("overlimit");
}
$('#text_counter').text('Characters left: ' + left);
});
});
Add this
$("#text_counter").text(150);
to your
btn.onclick
There is no need to mix both jquery and vanila script event handlers
$(document).ready(function() {
var limit = 15;
var $counter = $('#text_counter').text(limit);
var $input = $('#status').keyup(function() {
var left = limit - $(this).val().length;
$counter.toggleClass("overlimit", left < 0).text('Characters left: ' + left);
});
$('button').click(function() {
var val = $input.val();
if (val.length < 10) {
alert("Post must be at least 10 characters.");
return;
}
$('table').append('<tr><td>' + val + '</td></tr>');
$input.val('');
$counter.text(limit).removeClass('overlimit');
})
});
$(document).ready(function() {
var limit = 15;
var $counter = $('#text_counter').text(limit);
var $input = $('#status').keyup(function() {
var left = limit - $(this).val().length;
$counter.toggleClass("overlimit", left < 0).text('Characters left: ' + left);
});
$('button').click(function() {
var val = $input.val();
if (val.length < 10) {
alert("Post must be at least 10 characters.");
return;
}
$('table').append('<tr><td>' + val + '</td></tr>');
$input.val('');
$counter.text(limit).removeClass('overlimit');
})
});
input[type=text] {
padding: 5px;
border: 2px solid #000080;
-webkit-border-radius: 5px;
border-radius: 5px;
}
input[type=text]:focus {
border-color: #ccc;
}
-webkit-border-radius:5px;
border-radius:5px;
}
.rows {
text-align: center;
}
.postTable {
width: 400px;
height: 33px;
border: solid 1px lightgray;
border-width: 2px;
font-family: Verdana;
font-size: 20;
}
td {
border-bottom: solid 2px lightgray;
}
tr:last-child td {
border: none!important;
}
.overlimit {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="postBox">
<center>
<input type="text" id="status" name="post" maxlength="150" /> <span id="text_counter"></span>
<br>
<br/>
<button style="border : solid 0px #000080; border-radius : 4px; moz-border-radius : 4px; -webkit-box-shadow : 0px 0px 5px rgba(0, 0, 0, 1.0); -moz-box-shadow : 0px 0px 5px rgba(0,0,0,1.0); box-shadow : 0px 0px 5px rgba(0,0,0,1.0); font-size : 24px; font-style : ;color : #ffffff; padding : 4px 10px; background-color : #000080;">subpost</button>
<br/>
<br/>
<table name="rows" class="postTable"></table>
<td></td>
<tr></tr>
</center>
</div>
Try adding this on your page onload event:
$(document).ready(function(){$('#status').focus(left=(150-inpt.value.length));});
In that code snippet, I've assumed that your textbox's id is "status" and "left" is declared as a global variable. I can't try your code to fiddle. I think fiddle is acting funny right now.
Related
I create the checkout page of an eshop and I have a loop in which I display the products that the user has added to the cart. Inside the loop, I display the info for the products I have a text area so the user can choose the quantity of each product. The problem is that the id of each text area must be unique. How can I create many textareas in a loop with different ids?
textarea:
<form name='txtAreaForm' method='GET'>
<textarea disabled name='textArea' id='counter'></textarea>
</form>
Also, I have two buttons (+-) to change the value of the textarea, this is the .js file:
var counter = 1;
// Display total
$("#counter").text(counter);
// When button is clicked
$("#plusButton").click(function(){
counter = counter + 1;
$("#counter").text(counter);
});
//Subtract
$("#minusButton").click(function(){
if (counter>1) {
counter = counter - 1;
$("#counter").text(counter);
}
});
Though the question is not quite clear to me, you can do something like the following:
var counter = 1;
// Display total
$("#counter").text(counter);
var counter = counter + 1;
for(var i=0; i<5; i++){
$("form").append('<textarea name=textArea"+counter+" id=counter"+counter+">1</textarea><input class="plus" type="button" value="+" /><input class="minus" type="button" value="-" /><br>');
}
// When button is clicked
$(".plus").click(function(){
var txtArea = $(this).prev('textarea').text();
$(this).prev('textarea').text(parseInt(txtArea)+1);
});
//Subtract
$(".minus").click(function(){
var txtArea = $(this).prev().prev('textarea').text();
if(txtArea >=2){
$(this).prev().prev('textarea').text(parseInt(txtArea)-1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name='txtAreaForm' method='GET'>
</form>
You can use just JavaScript to render a form with as many textareas with its id as necessary and set the actions to each button related to each of them.
See this demo:
(function() {
// Set the plus action on every button with the class name «plus».
function setPlusAction() {
function plus(e) {
var textarea = e.target.previousSibling; // Find the textarea element related to the button clicked.
textarea.value = textarea.value * 1; // Convert the value into number.
textarea.value++; // Increment its value.
}
var elems = document.getElementsByClassName("plus"), i, len = elems.length, button;
for (i = 0; i < len; i++) {
button = elems[i]; // Find the current button.
button.onclick = plus; //Set the «plus» function on every button which has been found.
}
}
// Set the minus action on every button with the class name «minus».
function setMinusAction() {
function minus(e) {
var textarea = e.target.previousSibling.previousSibling; // Find the textarea element related to the button clicked.
textarea.value = textarea.value * 1; // Convert the value into number.
if (textarea.value > 1) {
textarea.value--; // Decrement its value.
}
}
var elems = document.getElementsByClassName("minus"), i, len = elems.length, button;
for (i = 0; i < len; i++) {
button = elems[i]; // Find the current button.
button.onclick = minus; //Set the minus function on every button which has been found.
}
}
// Render a form with the quantity of textareas required.
function buildForm(textareas) {
var html = "<form name=\"txtAreaForm\" method=\"GET\">", i;
for (i = 0; i < textareas; i++) {
html += "<div><textarea disabled name=\"textArea\" id=\"textarea";
html += i;
html += "\">1</textarea><button class=\"plus\" type=\"button\">+</button><button class=\"minus\" type=\"button\">-</button></div>";
}
html += "</form>";
return html; // Return the html content with the form.
}
/*
1. Render the form with document.getElementById("div").innerHTML = buildForm(50);
2. Once the form is renderd call setPlusAction() function;
3. And call setMinusAction() function;
*/
document.getElementById("div").innerHTML = buildForm(50); // Set 50 textareas.
setPlusAction();
setMinusAction();
})();
#div div {
border: solid 1px #ccc;
margin: 2px;
padding: 2px;
}
button.plus,
button.minus {
cursor: pointer;
}
<div id="div"></div>
Update:
jQuery version:
$(function() {
// Render a form with the quantity of textareas required.
function buildForm(textareas) {
var html = "<form name=\"txtAreaForm\" method=\"GET\">", i;
for (i = 0; i < textareas; i++) {
html += "<div><textarea disabled name=\"textArea\" id=\"textarea";
html += i;
html += "\">1</textarea><button class=\"plus\" type=\"button\">+</button><button class=\"minus\" type=\"button\">-</button></div>";
}
html += "</form>";
return html; // Return the html content with the form.
}
$("#div").html(buildForm(50)); // Render the form with 50 textareas.
$(".plus").on("click", function() {
var texarea = $(this).prev(), value = texarea.val() * 1;
value++;
texarea.val(value);
});
$(".minus").on("click", function() {
var texarea = $(this).prev().prev(), value = texarea.val() * 1;
if (value > 1) {
value--;
texarea.val(value);
}
});
});
#div div {
border: solid 1px #ccc;
margin: 2px;
padding: 2px;
}
button.plus,
button.minus {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="div"></div>
Remember: IDs must be unique.
I prefer using a class, because I think it is more clear for the code.
Example: my_set_Of_Text_area.add ('<div><span> Ananas : </span>','</div>');
I prefer using data to made the link with the counting area and the + / - buttons.
$(function() {
class TxtAreaFab {
constructor(Form_ID, TextAreaPrefix, BtPlusClass, BtMinusClass) {
this._ref = 0;
this._TaP = TextAreaPrefix;
this._BtPlus = BtPlusClass;
this._BtMinus = BtMinusClass;
this._$ID = $('#' + Form_ID);
}
add(before, after) {
var elements = before;
this._ref++;
elements += "<textarea disabled id='TxtArea_" + this._ref + "'>1</textarea>";
elements += "<button class=" + this._BtPlus + " data-ref=\"TxtArea_" + this._ref + "\">+</button>";
elements += "<button class=" + this._BtMinus + " data-ref=\"TxtArea_" + this._ref + "\">-</button>";
elements += after;
$(elements).appendTo(this._$ID);
}
/* ----- not used , just here for sample
clear () {
this._$ID.html('');
this._ref = 0;
}
*/
};
var my_set_Of_Text_area = new TxtAreaFab('txtAreaForm', 'zoneTA_', 'ClassBtPlus', 'ClassBtMinus');
my_set_Of_Text_area.add('<div><span> Apples : </span>', '</div>');
my_set_Of_Text_area.add('<div><span> Oranges : </span>', '</div>');
my_set_Of_Text_area.add('<div><span> Pears : </span>', '</div>');
my_set_Of_Text_area.add('<div><span> Bananas : </span>', '</div>');
$('#txtAreaForm').on('click', "button", function(e) {
e.stopPropagation();
var $txtArea = $("#" + $(this).data("ref")),
v = parseInt($txtArea.val());
if ($(this).hasClass('ClassBtPlus')) $txtArea.val(++v);
if ((v > 1) && ($(this).hasClass('ClassBtMinus'))) $txtArea.val(--v);
return false;
});
my_set_Of_Text_area.add('<div><span> Ananas : </span>', '</div>');
});
#txtAreaForm div {
clear: both;
height: 30px;
}
#txtAreaForm div span {
display: block;
float: left;
width: 120px;
font-weight: bold;
text-align: right;
padding-right: 10px;
}
#txtAreaForm textarea {
display: block;
float: left;
width: 40px;
height: 16px;
font-weight: bold;
text-align: center;
resize: none;
}
<form name='txtAreaForm' id='txtAreaForm' method='GET'></form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Special Fun solution! (but real).
I did it with only 9 lines of JavaScript / jQuery, and a little more in CSS.
And no need for textarea id. (Ok, my 2 "if" statements have only 1 line).
For the HTML part, each text box is placed in a "p" (paragraph), and that's it:
<p><textarea disabled > 1 </textarea></p>
<p><textarea disabled > 2 </textarea></p>
<p><textarea disabled > 3 </textarea></p>
The trick is in the CSS where I use :after and :before like the "+" or "-" buttons.
placed to the right of each box "p".
form p:after {
right: -22px;
content:'+';
...
form p:before {
right: -43px;
content:'-';
In the jQuery part.
I use the relative position of the mouse click to determine whether the operation should be a plus or minus. For the little story: -- $ (this) .outerWidth (); -- Is usefull.
Of course, it would still be better to add an ID on each textarea; but after reflection, it appeared to me that these input fields could be generated at the PHP server (?).
So, strange as it may seem, this solution is very serious. ;)
Everything is in the snippet.
$(function() {
$('form p').click(function(e) {
var
posX = (e.pageX - $(this).offset().left) - $(this).outerWidth();
Sign = (posX > 22) ? "moins" : (posX > 0) ? "plus" : "none",
Valn = parseInt($(this).children('textarea').text());
if (Sign === 'plus') $(this).children('textarea').text(++Valn);
if ((Sign === 'moins') && (Valn > 1)) $(this).children('textarea').text(--Valn);
});
});
textarea,
form,
p,
textarea {
font-family: Tahoma, sans-serif;
font-size: 16px;
}
textarea {
float: left;
width: 40px;
height: 22px;
font-weight: bold;
text-align: center;
resize: none;
line-height: 20px;
}
form p {
box-sizing: border-box;
display: block;
float: left;
clear: both;
position: relative;
border: 0;
margin: 5px 0 0 20px;
padding: 0;
}
form p:before,
form p:after {
position: absolute;
top: 2px;
width: 20px;
height: 20px;
display: block;
color: white;
background-color: darkslategray;
text-align: center;
font-size: 18px;
}
form p:after {
right: -22px;
content: '+';
line-height: 18px;
}
form p:before {
right: -43px;
content: '-';
line-height: 16px;
}
<form name="txtAreaForm" method='GET'>
<p><textarea disabled> 1 </textarea></p>
<p><textarea disabled> 2 </textarea></p>
<p><textarea disabled> 3 </textarea></p>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
I'm trying to create list of suppliers (checkboxes + labels) and search field to filter suppliers. I managed to get list renderered and after first load it works fine, but after I search through supplier list first click on checkbox doesn't work. I need to click twice for checkbox to become checked.
screenshot
I need checkbox to become checked after first click when searching through supplier list. Please help.
I created this fiddle here
HTML:
<div class="col-sm-12">
<div class="infoBlock suppliersWrapper">
<div class="blockTitle">Supplier:</div>
<div class="blockContent">
<p class="checkedSupliersTitile">Supplier list:</p>
<div class="row">
<div class="col-sm-12 col-lg-8">
<input type="text" class="form-control stickTop" placeholder="Search..." id="SearchSupplierInput">
<ul class="supplierList scrollable" id="suppliers"></ul>
</div>
<div class="col-sm-12 col-lg-4">
<p class="checkedSupliersTitile">Checked suppliers:</p>
<p class="checkedSupliersText" id="checkedSuppliers">no suppliers selected</p>
</div>
</div>
</div>
</div>
</div>
CSS:
.supplierList label {
color: #575757;
display: block;
font-size: 15px;
font-weight: 400;
cursor:pointer;
font-family: 'Ubuntu', sans-serif;
}
.supplierList input[type="checkbox" ]{
width : 2em;
margin : 0;
padding : 0;
font-size : 1em;
opacity : 0;
}
.supplierList input[type="checkbox" ] + label{
display : inline-block;
margin-left : -1em;
line-height : 1.5em;
position:relative;
z-index: 33;
}
.supplierList input[type="checkbox"] + label::before {
border: 1px solid #d6d6d6;
border-radius: 1px;
content: "";
height: 20px;
left: -1.8em;
position: absolute;
top: 0.06em;
width: 20px;
-webkit-box-shadow: 3px 3px 0 0 rgba(25, 24, 25, 0.04) inset;
-moz-box-shadow: 3px 3px 0 0 rgba(25, 24, 25, 0.04) inset;
box-shadow: 3px 3px 0 0 rgba(25, 24, 25, 0.04) inset;
background: #ffffff;
}
.supplierList input[type="checkbox" ]:checked + label:before{
background:#46c87c;
}
.supplierList input[type="checkbox"]:checked + label::after {
color: #fff;
content: "";
font-family: "fontawesome";
left: -1.6em;
position: absolute;
top: 0;
}
JavaScript:
$(document).ready(function() {
var SupplierList = [{"name":"125","id":"1"},
{"name":"2Bit Telecom Corporation","id":"2"},
{"name":"Alleven Telecom Corp Standart","id":"3"}];
var selectedSuppliers = [];
// Собираем и фильтруем активных поставшиков
renderSupplierList(SupplierList);
$("#SearchSupplierInput").on("change paste keyup", function() {
var userInput = $(this).val();
var my_json = JSON.stringify(SupplierList);
var filtered_supplierList = find_in_object(JSON.parse(my_json), {name:userInput});
if (userInput.length >= 3) {
$("#suppliers").html("");
renderSupplierList(filtered_supplierList);
} else if(!userInput) {
$("#suppliers").html("");
renderSupplierList(SupplierList);
}
});
function renderSupplierList(array) {
array.forEach(function(item, i) {
if(typeof selectedSuppliers["id"+item.id] === 'undefined') {
var ifCheckd = "";
}
else {
var ifCheckd = "checked";
}
$("#suppliers").append('\
<li><span>\n\
<input class="supplierSelect" type="checkbox" id="supplier'+i+'" ' + ifCheckd + ' name="supplier" value="'+ item.id +'"> \n\
<label for="supplier'+i+'">'+ item.name +'</label>\n\
</span></li>');
});
}
function find_in_object(my_object, my_criteria) {
return my_object.filter(function(obj) {
//console.log(obj);
return Object.keys(my_criteria).every(function(c) {
//if (obj[c].search(/my_criteria[c]/i) == -1) {
if (obj[c].search(new RegExp(my_criteria[c], "i")) == -1) {
return false;
} else {
return true;
}
});
});
}
$('.supplierList').on('change', 'input[type=checkbox]', function() {
supplierCheckboxChange(this);
});
function sortSingle(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
function supplierCheckboxChange(currEl) {
var cText = $( currEl ).siblings("label").text();
var cID = "id" + currEl.value;
if(currEl.checked) {
selectedSuppliers[cID] = cText;
}
else {
delete selectedSuppliers[cID];
}
var tmpSuppl = [];
for (var key in selectedSuppliers) {
tmpSuppl.push(selectedSuppliers[key]);
}
tmpSuppl.sort(function(a, b) {
var x = a.toLowerCase(); var y = b.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
var suppliers = tmpSuppl.join(', ');
if (!suppliers) {
suppliers = "no suppliers selected";
}
$('#checkedSuppliers').text(suppliers);
}
});
This happens because your renderList function is being called more than once. First keyup is triggered when you press a key and then when text box looses focus(when you click on checkbox) change is triggered.
This causes your renderList method to get executed twice and the checked checkbox gets replace by a new checkbox.
To fix this, just change
$("#SearchSupplierInput").on("change paste keyup", function() { ... }
To
$("#SearchSupplierInput").on("paste keyup", function() { ... }
Have a look at this fiddle and check the console. https://jsfiddle.net/nh7u4Lck/2/
I am not exprienced javascript programmer so I try to play with javascript. I am trying to make a slideshow by clicking on a button. Function I am trying to make a function with array that holds the names of all the images and changing the background-image according to the index of the array. I did only this part of function yet and I cant get what is wrong.
function change(lol){
var img = ["veni1.jpg", "veni2.jpg", "veni3"];
var middle = document.getElementById("vvvmiddle");
var index = img.indexOf(middle.style.backgroundImage);
if(change === "right"){
var current = index + 1;
middle.style.backgroundImage = img[current];
}
}
middle {
width:1262px;
height:550px;
background-color: white;
margin-left: -7px;
}
#vvvmiddle {
width:700;
height:400;
background-image:url('veni1.jpg');
margin: 20px 0px 0px 310px;
float:left;
}
#sipka {
width:40;
height:40;
border-radius: 100px;
background-color: #DCDCDC;
float:right;
margin: 450px 410px 0px 0px;
}
#sipkatext {
font-family: Impact;
color: white;
font-size: 30px;
padding-left: 10px;
padding-top: 1px;
}
#sipkaurl {
text-decoration: none;
}
#sipka:hover {
background-color: #3399FF;
}
#sipka2:hover {
background-color: #3399FF;
}
#sipka2 {
width:40;
height:40;
border-radius: 100px;
background-color: #DCDCDC;
float:right;
margin: 450px -100px 0px 0px;
}
#sipkatext2 {
font-family: Impact;
color: white;
font-size: 30px;
padding-left: 13px;
padding-top: 1px;
}
<div id="middle">
<div id="vvvmiddle">
<div id="sipka" onclick="change('left')">
<div id="sipkatext">
<</div>
</div>
<div id="sipka2" onclick="change('right')">
<div id="sipkatext2">></div>
</div>
</div>
</div>
A possible solution may be this one:
var img = ["img1.png", "img2.png", "img3.png"];
var len = img.length;
var url = 'Some url...';
var current=0;
var middle = document.getElementById("vvvmiddle");
middle.style.backgroundImage = "url(" + url + img[current] + ")";
function change(dir){
if(dir == "right" && current < len-1){
current++;
middle.style.backgroundImage = "url(" + url + img[current] + ")";
} else if(dir == "left" && current > 0){
current--;
middle.style.backgroundImage = "url(" + url + img[current] + ")";
}
}
See it in action, check here jsfiddle.
You can try with that:
function change(lol) {
var img = ["veni1.jpg", "veni2.jpg", "veni3"];
var middle = document.getElementById("vvvmiddle");
var index = img.indexOf(middle.style.backgroundImage);
if(lol === "right"){
index = (index + 1) % img.length;
} else {
index = (index + img.length - 1) % img.length;
}
middle.style.backgroundImage = img[index];
}
You are checking wrong variable in condition, it should be lol, not change:
if(lol === "right"){
var current = index + 1;
middle.style.backgroundImage = img[current];
}
Also you should handle "last image" case like Nicolas suggests.
I'm trying to create popup that can show when mouse over it and will stay when click on the link .The problem is I already make the popup will show up when the mouse over it but it will disappear when the mouse leave .How can I make the popup will stay show up when clicked .This is my code :
HTML
<div id="pop1" class="popbox">
<h2>Job Info Search</h2>
<h2>WRKNo : <input type="text" /></h2>
<h2>Result</h2>
<p>Customer Name : <input type="text" /></p>
<p>Caller Number : <input type="text" /></p>
<p>Complosed : <input type="text" /></p>
<p>Cate : <input type="text" /></p>
<p>Det : <input type="text" /></p>
<p>Feedback : <input type="text" /></p>
<p>WRKNo : <input type="text" /></p>
</div>
This is a popbox test. Hover here to see how it works.
CSS
.popbox {
display: none;
position: absolute;
z-index: 99999;
width: 400px;
padding: 10px;
background: #EEEFEB;
color: #000000;
border: 1px solid #4D4F53;
margin: 0px;
-webkit-box-shadow: 0px 0px 5px 0px rgba(164, 164, 164, 1);
box-shadow: 0px 0px 5px 0px rgba(164, 164, 164, 1);
}
.popbox h2
{
background-color: #4D4F53;
color: #E3E5DD;
font-size: 14px;
display: block;
width: 100%;
margin: -10px 0px 8px -10px;
padding: 5px 10px;
}
Javascript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script>
$(function() {
var moveLeft = 0;
var moveDown = 0;
$('a.popper').hover(function(e) {
var target = '#' + ($(this).attr('data-popbox'));
$(target).show();
moveLeft = $(this).outerWidth();
moveDown = ($(target).outerHeight() / 2);
}, function() {
var target = '#' + ($(this).attr('data-popbox'));
$(target).hide();
});
$('a.popper').mousemove(function(e) {
var target = '#' + ($(this).attr('data-popbox'));
leftD = e.pageX + parseInt(moveLeft);
maxRight = leftD + $(target).outerWidth();
windowLeft = $(window).width() - 40;
windowRight = 0;
maxLeft = e.pageX - (parseInt(moveLeft) + $(target).outerWidth() + 20);
if(maxRight > windowLeft && maxLeft > windowRight)
{
leftD = maxLeft;
}
topD = e.pageY - parseInt(moveDown);
maxBottom = parseInt(e.pageY + parseInt(moveDown) + 20);
windowBottom = parseInt(parseInt($(document).scrollTop()) + parseInt($(window).height()));
maxTop = topD;
windowTop = parseInt($(document).scrollTop());
if(maxBottom > windowBottom)
{
topD = windowBottom - $(target).outerHeight() - 20;
} else if(maxTop < windowTop){
topD = windowTop + 20;
}
$(target).css('top', topD).css('left', leftD);
});
});
</script>
Any ideas how I can do this?
Try this:
$('a.popper').hover(function (e) {
var target = '#' + ($(this).attr('data-popbox'));
$(target).show();
moveLeft = $(this).outerWidth();
moveDown = ($(target).outerHeight() / 2);
}, function () {
var target = '#' + ($(this).attr('data-popbox'));
if (!($("a.popper").hasClass("show"))) {
$(target).hide(); //dont hide popup if it is clicked
}
});
$('a.popper').click(function (e) {
var target = '#' + ($(this).attr('data-popbox'));
if (!($(this).hasClass("show"))) {
$(target).show();
}
$(this).toggleClass("show");
});
FIDDLE here.
Use the click method in jquery, so like $('a.popper').click(); and pass in parameters in the click method that have the popup show, similar to how you are using the hover method and the mouseover method
I wanted to create a Cash Register Effect using Pure Javascript(With out using any libraries),
Here is the link for Cash register Effect which is implemented Using Mootools,
http://jsbin.com/ehuzes/edit#preview
I want to get this effect using raw Javascript. It will be huge help, If somebody gives the solution.
$('#number').on('change', function (e) {
$(this).cashregister($(this).val());
});
(function ($) {
$.fn.cashregister = function (num) {
var output = $('#output').html();
function intervalfunc(interval, num) {
var end = parseInt($('#number').html());
var cont = parseInt($('#output').html())
$('#output').html( cont + interval );
if ( $('#output').html() == num ) {
clearInterval(int);
return false;
}
}
if (num > output) {
var int = setInterval(function() { intervalfunc(1, num) }, 0.1);
}else if (num < output) {
var int = setInterval(function() { intervalfunc(-1, num) }, 0.1);
}else if (num == $('#output').html() ) {
// do nothing
}else{
alert("Invalid Input!");
}
};
})(jQuery);
http://jsfiddle.net/DuLjC/3/ -> working version of suggested fix
use an onclick function on a button or something, which should get the number (value from maybe a text box) and to send that variable to a defined function which uses .innerHTML on a div to change the number value, then you use SetInterval function to make the number go either up or down by 1 each interval. then use clearInterval when the number has been reached.
maybe something like:
<div id = "container">0</div>
<input type = 'text'
id = 'number' />
<input type = 'button'
value = 'change amount'
onclick = "var num = document.getElementById('number').value;
cashregister(num);" />
for the HTML and:
<script type = "text/javascript">
function cashregister(num) {
var cont = document.getElementById('container').innerHTML;
if (num < cont) {
var int = setInterval("intervalfunc(1)", (interval_time_in_miliseconds));
function intervalfunc(num) {
var end = document.getElementById('number');
var cont = document.getElementById('cont').innerHTML;
cont.innerHTML = cont + num;
if (cont == end) {
clearInterval(int);
}
}
} else if (num > cont) {
var int = setInterval("intervalfunc(-1)", (interval_time_in_miliseconds));
function intervalfunc(num) {
var end = document.getElementById('number');
var cont = document.getElementById('cont').innerHTML;
cont.innerHTML = cont + num;
if (cont == end) {
clearInterval(int);
}
}
} else if (num == cont) {
//do nothing
} else {
alert("invalid input!");
}
}
</script>
I'm not sure if this exact code will work but what you want is something along these lines.
I like this one by Nevan Scott: https://codepen.io/nevan/pen/uBkEr
var total = 0;
document.getElementById('entry').onsubmit = enter;
function enter() {
var entry = document.getElementById('newEntry').value;
var entry = parseFloat(entry);
currency = currencyFormat(entry);
document.getElementById('entries').innerHTML += '<tr><td></td><td>' + currency + '</td></tr>';
total += entry;
document.getElementById('total').innerHTML = currencyFormat(total);
document.getElementById('newEntry').value = '';
return false;
}
function currencyFormat(number) {
var currency = parseFloat(number);
currency = currency.toFixed(2);
currency = '$' + currency;
return currency;
}
body {
background: #EEE;
font-family: sans-serif;
font-size: 20px;
margin: 3em;
padding: 0;
}
#register {
width: 20em;
margin: auto;
}
#ticket {
background: white;
margin: 0 1em;
padding: 1em;
box-shadow: 0 0 5px rgba(0,0,0,.25);
}
#ticket h1 {
text-align: center;
}
#ticket table {
font-family: monospace;
width: 100%;
border-collapse: collapse;
}
#ticket td, #ticket th {
padding: 5px;
}
#ticket th {
text-align: left;
}
#ticket td, #ticket #total {
text-align: right;
}
#ticket tfoot th {
border-top: 1px solid black;
}
#entry {
background: #333;
padding: 12px;
border-radius: 10px;
box-shadow: 0 0 5px rgba(0,0,0,.25);
}
#entry input {
width: 100%;
padding: 10px;
border: 1px solid black;
text-align: right;
font-family: sans-serif;
font-size: 20px;
box-shadow: inset 0 0 3px rgba(0,0,0,.5);
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#entry input:focus {
outline: none;
border-color: rgba(255,255,255,.75);
}
<div id="register">
<div id="ticket">
<h1>Thank You!</h1>
<table>
<tbody id="entries">
</tbody>
<tfoot>
<tr>
<th>Total</th>
<th id="total">$0.00</th>
</tr>
</tfoot>
</table>
</div>
<form id="entry">
<input id="newEntry" autofocus placeholder="How Much?">
</form>
</div>