Here is the HTML:
<form>
<textarea id="input1"></textarea>
<textarea id="input2"></textarea>
<span></span>
</form>
the js:
$("#input2").keyup{
var a = document.getElementById("input1").length;
var b = document.getElementById("input2").length;
var c=a+b;
$("span").html(c);
}
each time 'c' reach multiple 140, i need it to be added by 'b',
I've try to do this:
while(c%140 == 0){
c=c+b;
}
at 140th keyup, yes its added, but next keyup(141th) and so on 'c' back to it's value added by notihng. How to do this correctly?
thanks.
I can't be sure that I'm reading this question correctly, but if my jsfiddle of your code is a close approximation, the solution may be as simple as getting rid of the var in front of c when you add a+b. If you want c to have a persistant value, you need its scope to be outside the keyup event handler.
From the fiddle:
$(function() {
var c = 0;
$("#input2").keyup( function() {
var a = $("#input1").val().length;
var b = $("#input2").val().length;
c=a+b;
if(c%140 == 0){
c=c+b;
}
$("span").html(b);
});
});
Notice that's an if, not a while. If it's supposed to be a while loop, that's an easy change to make.
Update
I think I have an idea what's going on here. You want to keep track of the total character count of your multi-page SMS messages. The updated jsfiddle has the answer to the question you wouldn't just come out and ask.
Here's the new code:
$(function() {
$("#input2, #input1").keyup( function() {
var a = $("#input1").val().length;
var b = $("#input2").val().length;
c=a+b;
c+=Math.floor(c/140)*b;
$("span").html(c);
});
});
Now, this of course assumes that input1 holds your actual message while input2 holds some text that needs to be displayed on each page. If it's the other way around, or if there's some other purpose for this code, please let me know.
Related
I would like to increase the font size of the paragraph as well as the font size of the number in the button.
I copied and pasted my sizer function from StackOverflow (a few alterations) and thought it would work and still can't get it to work. Can someone help?
Since I've spent so much time on just the first part, as a beginner programmer, I'm wondering what I am missing. Does anyone have any ideas from my code or their experience as to what I might be missing?
Thanks as always.
<html>
<button onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
sizer = function changeFontSize() {
div = document.getElementById("test");
currentFont = div.style.fontSize.replace("pt", "");
div.style.fontSize = parseInt(currentFont) + parseInt(clicks) + "pt";
}
</script>
</html>
Some things here:
I woudn't append two functions to your onclick here. Just append one and call your second function from the first one that gets fired via onclick. That looks a lot more tidy
Don't forget to put var before every variable, without it's not valid JavaScript
I didn't quite understand what you tried with your currentFont variable, so I removed it. It's not necessary and causes the script to not working correctly
<html>
<button onclick='incrementer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
var clicks = 0;
var incrementer = function() {
clicks += 1;
var click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
sizer();
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
div.style.fontSize = parseInt(clicks) + "pt";
}
</script>
</html>
Here's a from-scratch version that does what you're asking for. I'll point out a few things that I did to help you out.
https://codepen.io/anon/pen/VBPpZL?editors=1010
<html>
<body>
<button id="count">0</button>
<p id="test">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</p>
</body>
</html>
JS:
window.addEventListener('load', () => {
const button = document.querySelector('#count');
const paragraph = document.querySelector('#test');
const startingFontSize = window.getComputedStyle(document.body, null)
.getPropertyValue('font-size')
.slice(0, 2) * 1;
let clicks = 0;
button.addEventListener('click', () => {
clicks++;
// this is a template literal
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const fontSize = `${startingFontSize + clicks}px`;
button.innerHTML = clicks;
button.style.fontSize = fontSize;
paragraph.style.fontSize = fontSize;
});
});
The code runs when the page is loaded, so we attach an event listener on the window object listening for the load event.
We then store references to the button and the paragraph elements. These are const variables because their values won't change. This also limits their scope to the containing function.
We get the initial font size for the body element, because in this example we aren't explicitly setting a base font in css so we're just using the one for the document. getComputedStyle is a somewhat expensive operation, and in this case we only need to get it in the beginning because it won't change, so we also store it as a const. The value is returned as a string like "16px" but we need the number, hence the slice and multiplying by one to cast the string into a number. parseInt would also do the same thing.
Notice that clicks is defined with let. This means that the variable can be changed. var still works of course, but in modern practices its best to use const and let when declaring variables. This is partly because it forces you to think about what kind of data you're working with.
We add an event listener to the button element and listen for the click event. First, we increment the clicks variable. Then we declare fontSize using a template literal which adds our new clicks count to the startingFontSize and "px" to get a string.
Finally, the innerHTML value of the button element is updated. Then we update the fontStyle property for both elements.
The issue here is that there is no initial value for the fontSize of your <p> tag so div.style.fontSize returns an empty string.
You can use window.getComputedStyle instead of div.style.fontSize and you will get the current fontSize.
There is already a post explaining this method
https://stackoverflow.com/a/15195345/7190518
You don't have an initial font-size style on your <p> tag, so it div.style.fontSize is always empty. Also, best practice is to always use var when introducing new variables in javascript.
One good trick to help debugging things like these is to use console.log() at various points, and see whats coming out in your browser console. I used console.log(div.style.fontSize) and the answer became clear.
Working below after adding <p style='font-size:12px'>a</p>:
<html>
<button style='font-size:12px;' onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test' style='font-size:12px;'>a</p>
<script>
var clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
var btn = document.getElementById("count");
var newSize = parseInt(div.style.fontSize.replace("pt", "")) + parseInt(clicks);
div.style.fontSize = newSize + "pt";
btn.style.fontSize = newSize + "pt";
}
</script>
</html>
I don't understand the logic of this solution, but you can simplify it avoiding to use a lot of var (anyway always prefer let or const if you don't need to change), using a single function and writing less code.
function increment(e){
const ctrl = document.getElementById('test');
let current = parseInt(e.dataset.size);
current += 1;
e.innerHTML = current;
e.dataset.size = current;
ctrl.style.fontSize = current + 'pt';
}
<button onclick="increment(this);" data-size="20">20</button>
<p id='test' style="font-size:20pt;">A</p>
Is it possible to make javascript to when you enter variables to add code to html..? I don't know English too good, so..I'm going to draw it!
Also, I don't want it to change everything, but I want it just to add that
info to the list..I have premade HTML page with linked CSS.
If you have any questions, please ask me, just help me.. :(
I know HTML and CSS, java..Not even a little bit.. :/
If you are here reading this, THANK YOU! <3
You have many options to add html to your page through JavaScript.
1) Simply create a div with an id
<div id="enterTextHere"></div>
2) Inside of your custom.js file or inside of <script></script>, you can use many different methods
Method 1 : Using innerHTML
var desiredElement = document.getElementById("enterTextHere");
desiredElement.innerHTML = "<p>I added text!</p>";
Method 2 : Using JQuery.append
$("#enterTextHere").append("I added text!");
I'm sure there are many more but without your specific code to reference this is the best I can do. Please use this link for your reference. It also has a lot of good information for the rest of your HTML journey. Enjoy! w3schools
Maybe something like this can help:
HTML:
<table class="table"><tr id="update-table"></tr></table>
<script>
(function(){
var updater = (function(){
function updater( options ){
this.table = options.table;
this.cells = this.table.querySelectorAll('.cell');
this.num_cells = this.cells ? this.cells.length : 0;
}
updater.prototype.update_element = function( index, value ){
this.cells[index].innerHTML = value;
};
updater.prototype.add_element = function(){
var td = document.createElement('td');
td.setAttribute('class','cell');
this.table.appendChild(td);
this.cells.push(td);
this.num_cells++;
};
return updater;
})();
window.updater = updater;
})();
var table, a, count = 0;
table = document.getElementById('update-table');
a = new updater({table:table});
for(var i = 0; i < 5; ++i){
a.add_element();
a.update_element(i,'info'+i);
}
</script>
My goal is to have a button (controlled by a javascript function) that would toggle the entire CSS on the website on and off. I thought this was a common practice and was surprised when I couldn't find a complete solution here or on the web.
Here is what I got.
$("#button").click(function() {
var css = (document.styleSheets[0].enabled = true);
if (css == true)
{
document.styleSheets[0].disabled = true;
css = (document.styleSheets[0].enabled = false);
}
else if (css == false)
{
document.styleSheets[0].disabled = false;
}
});
A simple Jquery function that targets the button by ID and performs an if test. I could've ommited the variable, but this way I am able to check the value easily in console.log. I am able to turn the CSS off, but not back on. The program doesn't even get to the else condition.
I am aware that the else if is not really appropriate, but with just else (and even just with another if condition) the function doesn't run at all.
Second option that I thought of, and which might be much easier is just dynamically changing the contents of the link href attribute, where the path to the css file is given.
But I am struggling to target the href element with Javascript.
This is a simple Boolean toggle so write it as a simple toggle
$("#button").click(function() {
var sheet = document.styleSheets[0];
sheet.disabled = !sheet.disabled;
});
As for why your code isn't working as is,
var css = (document.styleSheets[0].enabled = true);
// same as
var css;
document.styleSheets[0].enabled = true;
css = true;
which means
if (css == true)
// same as
if (true == true)
which always holds so you'll always follow this code path
Well, for one you need to loop through all of the stylesheets.
Also, you can save some lines of code by using a counter, then on each button click increment the counter and use the % modulo operator to turn that into a 1 or a 0, which you can then coerce a boolean from using !!.
var count = 0;
var sheets = document.styleSheets;
$("#button").click(function() {
for(var i in Object.keys(sheets)) sheets[i].disabled = !!(++count % 2);
});
.demo {
background: #888;
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="demo">Some Text</div>
<button id="button">Click It</button>
Your problem is that you are doing an assignment when you should be doing an equality check.
You have
var css = (document.styleSheets[0].enabled = true);
But you are really trying to do an equality check, i.e.,
var css = (document.styleSheets[0].enabled == true);
Notice the extra =. The single = does an assignment, so your current code is equivalent to this:
document.styleSheets[0].enabled = true
var css = document.styleSheets[0].enabled; // i.e., true
Because you set enabled to true, your if (css == true) condition is always satisfied, so your code always turns the CSS off and never turns it back on.
The fix, as Paul S. wrote in his answer, is just to toggle the value of document.styleSheets[0].disabled, as in:
$("#button").click(function() {
document.styleSheets[0].disabled = !document.styleSheets[0].disabled;
});
There's no need to set and track a new property enabled.
The issue seems to be that you are doing assignment, and not comparison, on this line:
var css = (document.styleSheets[0].enabled = true);
It should be
var css = (document.styleSheets[0].enabled == true);
Probably simpler, since you have a jquery tag on the question, to just do:
$stylesheets = $('link[rel="stylesheet"]');
$("#button").click(function() {
$stylesheets.attr('disabled', !$stylesheets.attr('disabled'));
});
If you want to modify every href in your DOM,
just use
$('a[href*=]').each(function () {
var $this = $(this);
$this.attr('href', $this.attr('href').replace();
});
I have been able to make some progress on a program but am running into a problem that I can't quite figure out. In the script, when the text box loses focus it is supposed to update the total cost. At this point it retrieves the number from the html code, but it is not retrieving the number that is input.
function productCosts()
{
var totalMap = document.getElementById('qty1');
var quantity1 = parseFloat($("qty1").value);
var price1 = parseFloat($('price1').value);
var totalMapBlur = function()
{
var totalMapCost = $('cost1');
totalMapCost = (quantity1) * (price1);
alert(price1);
alert(quantity1);
alert(totalMapCost);
}
qty1.onblur = (totalMapBlur);
}
I have created a fiddle so that you can see all of the code. http://jsfiddle.net/KRFjd/1/
Any help is greatly appreciated.
P.S. If you feel my question is not written well enough, please let me know how to improve, don't just review the question negatively. I am trying.
The problem is that you only set quantity1when you call productCosts() when the document is first loaded. You don't update it when the user edits the input field. And if you want the Cost column to be updated, you have to assign to its value.
var totalMapBlur = function()
{
var quantity1 = $('qty1').value;
var totalMapCost = (quantity1) * (price1);
alert(price1);
alert(quantity1);
alert(totalMapCost);
$('cost1').value = totalMapCost;
}
FIDDLE
So I am trying to make something where whenever I click on the text it change's color.
Javascript:
function changecolor(){
var tc = document.getElementById("header").style.color.value;
if (tc = "#000000") { tc = "#0009FF"}
else if (tc == "#0009FF") { tc = "#FF0000"}
else if (tc == "#FF0000") { tc = "#15FF00"}
else if (tc == "#15FF00") { tc = "#FFA600"}
else {tc = "#000000"};
document.getElementById("header").style.color.value = tc;
}
html:
<div onclick="changecolor()"><h1 id="header" style="color:#000000;"> Nick's Basic Physic's Calculator </h1></div>
It is not working and I have not been able to figure out why. When I click on the text nothing happens.
Change
document.getElementById("header").style.color.value = tc;
to
document.getElementById("header").style.color = tc;
Working example:
http://jsfiddle.net/xEyLf/
your problem is in var tc = document.getElementById("header").style.color.value;
you have to change to tc = document.getElementById("header").style.color;in order to get the color into variable.
I have another solution... here's a jsfiddle: http://jsfiddle.net/9zfJA/
Keep in mind I'm using these jQuery methods (as well as the jQuery library itself), by simply switching between CSS classes:
hasClass(): to check if the class is present
addClass(): to add the correct class based on the condition above
removeClass(): remove all classes, I've basically built a "reset" function
I think there are errors in the way it functions and how you want it, but I've built it on the same logic you have in your question.