I have four dynamic variables in my program,
xzero, xone, xtwo, xthree
That represent the coefficients of a cubic function. I want to show the actual equation in the HTML, in the following format:
xthree*x^3+xtwo*x^2+xone*x+xzero=f(x)
but it needs to be able to update with the variables, so I had originally thought that I would do a
document.getElementById("demo").innerHTML = (new equation);
But it seems to me that either mathJax doesn't work in javascript, or that I'm not doing it right. The only alternative solution that I could think of is to make four individual div tags per variable, and update them all, but this seems unnecessarily clunky. Could I get some pointers either way as to how I would fix this?
MathJax automagically renders the document when it is loaded, but not later. Try explicitly requesting re-render:
document.getElementById("demo").innerHTML = "...";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, 'demo']);
EDIT: After some thinking, I figured you could ask for the render in one element, keep it hidden, then copy the finished markup into another, to prevent flicker:
var mathDiv = document.getElementById('math');
var displayDiv = document.getElementById('display');
MathJax.Hub.Queue(["Typeset",MathJax.Hub,"math"]);
MathJax.Hub.Queue(function() {
var math = MathJax.Hub.getAllJax("MathDiv")[0];
var i = 1;
setInterval(function() {
MathJax.Hub.Queue(["Text", math, "\\int_0^{" + i + "} x dx"]);
MathJax.Hub.Queue(function() {
displayDiv.innerHTML = mathDiv.innerHTML;
});
i++;
}, 1000);
});
#math {
display: none
}
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<div id="math">$$$$</div>
<div id="display"></div>
Related
I'm having a bit a trouble with creating a category filter for my custom post type taxonomy, I've tried allot of different things in jQuery and I think this should be the best way to get what I want.
Code:
var divs;
$('.category').on('click', function() {
if(divs == 1) {
alert('ayylmao?');
$('section#showcase').append(detached);
divs = 0;
} else {
divs = 1;
var lolxd = $(this).find('a').attr('id');
alert(lolxd);
var detached = $('section#showcase').contents().not("." + lolxd).detach();
}
});
It has been a while ago that I used jQuery but for some reason the var 'detached' wont append to the section showcase.
Would like to hear what I am doing wrong ;_;
detached is declared within your click handler function. That means it's re-created every time the function runs.
Contrast that to your use of divs which is declared outside the function and thus persists across function calls.
There are many ways to solve this, but the simplest would be to follow the same pattern that you have for divs and have code that looks like this:
var divs;
var detached;
$('.category').on('click', function() {
if(divs == 1) {
alert('ayylmao?');
$('section#showcase').append(detached);
divs = 0;
} else {
divs = 1;
var lolxd = $(this).find('a').attr('id');
alert(lolxd);
detached = $('section#showcase').contents().not("." + lolxd).detach();
}
});
Speaking more generally, it sounds like when you detach a showcase, you want to keep it around so you can add it back later. Depending on the makeup of your program, it might be more useful to just change the display of that item to none. However, this does change the semantics if you had multiple things you could append to your showcase.
Is there anyway to use jQuery to dynamically set the attributes of HTML elements that are stored in variables?
For example, at one point in my application, a user creates a varying number of select input fields. For eventual processing by PHP, the elements need to be named in the format name='input'+siteNumber+'['+x+']', where x is the number of elements created in a for loop.
Here's a rough sketch of what I'm thinking needs to be done - THIS IS NOT FUNCTIONAL CODE, IT IS ONLY AN ILLUSTRATION.
$(".number_select").change(function(){
numberFound = $(this).val();
siteNumber = $(this).parent().attr('data-site_number');
//HERE'S THE INPUT TO BE NAMED
selectInput = "<select></select>";
this['inputArray' + siteNumber] = [];
for(x = 1; x <= numberFound; x++){
//THIS IS WHAT I'D LIKE TO ACCOMPLISH - SETTING THE ATTRIBUTE - THOUGH THIS UNDERSTANDABLY DOES NOT WORK IN THIS PARTICULAR FORMAT
this['inputArray' + siteNumber].push(selectInput.attr("name", "species"+siteNumber+"["+x+"]"));
};
$(this).parent().append(this['inputArray' + siteNumber]);
};
Thank you.
Thanks everyone - I actually ended up deciding to handle this a little differently, but it works perfectly - rather than storing the elements in variables, I used a function instead...
function inputs(siteNumber, x){
return ("<select name='selectInput"+siteNumber+"["+x+"]'>"+list+"</select>");
};
$(".number_select").change(function(){
numberFound = $(this).val();
siteNumber = $(this).parent().attr('data-site_number');
this['inputArray' + siteNumber] = [];
for(x = 1; x <= numberFound; x++){
this['inputArray' + siteNumber].push(inputs(siteNumber, x));
};
$(this).parent().append(this['inputArray' + siteNumber]);
};
Don't know why I didn't think of this in the first place, it seems obvious to me now. Oh well, live and learn.
To vaguely answer your question, you can dynamically generate an element and use jQuery's attr for adjusting the name attribute pretty easily like so.
var select = $('<select>').attr('name', 'add-name-here');
$('<option>').attr('value', 'some-value').text('Option').appendTo(select);
$('#wrapper').html(select);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper"></div>
Which outputs
<select name="add-name-here">
<option value="some-value">Option</option>
</select>
In your case, instead of adding it to #wrapper you would build up the select box as you need and append it to whichever select box has the change? Not sure your specific use case. Hope it helps.
<!DOCTYPE HTML>
<html>
<head>
<title> Javascript - stuff </title>
<script type="text/javascript">
<!--
function GetCountsAll( Wordcount, Sentancecount, Clausecount, Charactercount )
{
var TextString = document.getElementById("Text").innerHTML;
var Wordcount = 0;
var Sentancecount = 0;
var Clausecount = 0;
var Charactercount = 0;
// For loop that runs through all characters incrementing the variable(s) value each iteration
for (i=0; i < TextString.length; i++);
if (TextString.charAt(i) == " " = true)
Wordcount++;
return Wordcount;
if (TextString.charAt(i) = "." = true)
Sentancecount++;
Clausecount++;
return Sentancecount;
if (TextString.charAt(i) = ";" = true)
Clausecount++;
return Clausecount;
}
-->
</script>
</head>
<body>
<div id="Text">
It is important to remember that XHTML is a markup language; it is not a programming language. The language only describes the placement and visual appearance of elements arranged on a page; it does not permit users to manipulate these elements to change their placement or appearance, or to perform any "processing" on the text or graphics to change their content in response to user needs. For many Web pages this lack of processing capability is not a great drawback; the pages are simply displays of static, unchanging, information for which no manipulation by the user is required. Still, there are cases where the ability to respond to user actions and the availability of processing methods can be a great asset. This is where JavaScript enters the picture.
</div>
<input type = "button" value = "Get Counts" class = "btnstyle" onclick = "GetCountsAll()"/>
<br/>
<span id= "Charactercount"> </span> Characters <br/>
<span id= "Wordcount"> </span> Words <br/>
<span id= "Sentancecount"> </span> Sentences <br/>
<span id= "ClauseCount"> </span> Clauses <br/>
</body>
</html>
I am a student and still learning JavaScript, so excuse any horrible mistakes. The script is meant to calculate the number of characters, words, sentences, and clauses in the passage. It's, plainly put, just not working. I have tried a multitude of things to get it to work for me and have gotten a plethora of different errors but no matter what I can NOT get this to work. Please help! (btw i know i misspelled sentence)
Remove the semicolon from for (i=0; i < TextString.length; i++);. This breaks out of the loop.
Put brackets {} around
Sentancecount++;
Clausecount++; so they are incremented each time the full stop is seen. Currently only Sentance is incremented each time. Clause is incremented at the end of the text.
I would also use brackets generally after ifs. It makes for readability and you can see what the code is doing if you can read it easily.
Next, you can only have want one return from the method. Have the first method call the secondary ones if that makes sense. Set it so you get some variables being given values, and then print them out.
hth
You could use the split method of the string. Like this:
WordCount = TextString.split(' ').length;
Sentancecount = TextString.split('.').length;
Clausecount = TextString.split(';').length;
Charactercount = TextString.length;
This way, you don't need the for loop anymore.
Well, you have several issues here.
First, you want your for loops to have braces around the code you want to execute on each iteration.
for (i=0; i < TextString.length; i++) {
if (TextString.charAt(i) == " " = true)
Wordcount++;
}
(I'm assuming WordCount is supposed to be outside the loop (but it's incorrect either way))
Next, you're not handling those return values.
The way return works is that you can set a variable to the result of the function.
For example:
function x() {
return 2;
}
var i = 1;
var q = i + x(); // Add the result of the function to i
alert(q); // This will display 3
So by calling return, you're sending that value back to where the function was called, but you're never using it.
Also, calling return immediately exits the function. You do not want this if you want to continue processing. I suggest that you create variables for each of the three values and store the results to that. Then after your processing in the script, you can the innerHTML of a div to the them.
Here's an example that may help you:
<html>
<head>
<title>Example Javascript</title>
<script type="text/javascript">
function myFunction()
{
var text = Array(8).join(parseInt('')) + ' Batman!';
var element = document.getElementById("result");
element.innerHTML = text;
}
</script>
</head>
<body>
The output from our function is: <div id="result"> </div>
<br />
<button type="button" onclick="myFunction()">Run</button>
</body>
</html>
I would like to note that there are some really simple ways to solve this, but this seems like homework or at least a learning experience which is why I'm setting you on the right path rather than just giving you a straight answer. You're close! My advice is to just keep at it!
I'm trying to debug some javascript I wrote and can't figure out why it's not working. If I hard code the variables it works fine, but if I use document.getElementById('id').value to get the variable it fails.
The example below works fine but as soon as I un-comment the commented lines it doesn't. Printing the variables before and after the second section they seem to be identical.
Really don't get what's going on. Maybe I just need to sleep on it, but if anyone's got suggestions that would be great!
roof_width = 5;
roof_depth = 3;
panel_width = 2;
panel_depth = 1;
panel_power = 200;
roof_margin = 0.100;
panel_gap = 0.05;
roof_width = document.getElementById('roof_width').value;
roof_depth = document.getElementById('roof_depth').value;
// panel_width = document.getElementById('panel_width').value;
// panel_depth = document.getElementById('panel_depth').value;
panel_power = document.getElementById('panel_power').value;
// roof_margin = document.getElementById('roof_margin').value;
panel_gap = document.getElementById('panel_gap').value;
Are you trying to add numbers that are in text boxes? Because of the way JavaScript's variable typing system works (combined with the overloading of the + operator), 2 + 2 === 4 (adding numbers) but '2' + '2' === '22' (string concatenation). Try changing the lines to, for example:
panel_width = parseFloat(document.getElementById('panel_width').value);
or alternatively:
panel_width = Number(document.getElementById('panel_width').value);
This will ensure that JavaScript treats the numbers as numbers rather than as strings.
JavaScript parameters can't be called in the same way that you're calling HTML elements. In order to call
document.getElementById('roof_margin').value;
you need to assign 'roof_margin' to an HTML form element.
Pherhaps you have multiple dom elements with the same id? Remember the dom element ID must be unique. I suggest you to use jquery for interacting javascript with html.
Make sure your code is in an onload function. Otherwise the elements may not have been loaded into the DOM yet.
window.onload = funciton(){/* code here */};
What I want to do is that: a webpage with continuously updating content. (In my case is updating every 2s) New content is appended to the old one instead of overwriting.
Here is the code I have:
var msg_list = new Array(
"<message>Hello, Clare</message>", "<message>Hello,Lily</message>",
"<message>Hello, Kevin</message>", "<message>Hello, Bill</message>"
);
var number = 0;
function send_msg()
{
document.write(number + " " + msg_list[number%4]+'<br/>');
number = number + 1;
}
var my_interval = setInterval('send_msg()', 2000);
However, in both IE and Firefox, only one line is printed out, and the page will not be updated anymore. Interestingly in Chrome, the lines are being printed out continuously, which is what I am looking for.
I know that document.write() is called when the page is loaded according to this link. So it's definitely not the way to update the webpage continuously. What will be the best way to achieve what I want to do?
Totally newbie in Javascript. Thank you.
Lily
I would have a div or some other container, like this:
<div id="msgDiv"></div>
Then write to it like using .innerHTML, like this:
var msg_list = new Array(
"<message>Hello, Clare</message>", "<message>Hello,Lily</message>",
"<message>Hello, Kevin</message>", "<message>Hello, Bill</message>"
);
var number = 0;
function send_msg()
{
document.getElementById("msgDiv").innerHTML += number + " " + msg_list[number%4]+'<br/>';
number++;
}
var my_interval = setInterval(send_msg, 2000);
You can see a working example of this here
You can append to the innerHTML property:
var number = 0;
function send_msg()
{
document.getElementById('console').innerHTML += (number + " " + msg_list[number%4]+'<br/>');
number = number + 1;
}
This code will append the message to an element with an id of console, such as
<div id="console"></div>
By the way, it is bad practice to call setInterval with a string.
Instead, pass the function itself, like this:
var my_interval = setInterval(send_msg, 2000);
I would start by looking at the jQuery library. This will save you a lot of pain.
What you want to do is keep inserted lines into a table, using eg:
$('table tbody').append('<tr><td>some value</td></tr>');
This would be an excellent opportunity for you to learn a little DOM programming.
Using the DOM to update the page should result in less overhead than simply concatenating more HTML into it. Find the node you want to put the updates into, and do an appendChild on each subsequent addition.
The answers to this question may be helpful: What's a simple way to web-ify my command-line daemon?